001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.transport.tcp;
018
019import org.apache.activemq.command.Response;
020
021/**
022 * ResponseHolder utility
023 */
024public class ResponseHolder {
025    protected Response response;
026    protected Object lock = new Object();
027    protected boolean notified;
028
029    /**
030     * Construct a receipt holder
031     */
032    public ResponseHolder() {
033    }
034
035    /**
036     * Set the Response for this holder
037     *
038     * @param response
039     *      the response returned from the remote peer.
040     */
041    public void setResponse(Response r) {
042        synchronized (lock) {
043            this.response = r;
044            notified = true;
045            lock.notify();
046        }
047    }
048
049    /**
050     * Get the Response
051     *
052     * @return the Response or null if it is closed
053     */
054    public Response getResponse() {
055        return getResponse(0);
056    }
057
058    /**
059     * wait up to <Code>timeout</Code> timeout milliseconds to get a receipt
060     *
061     * @param timeout
062     * @return the Response that was set or null if none set yet.
063     */
064    public Response getResponse(int timeout) {
065        synchronized (lock) {
066            if (!notified) {
067                try {
068                    lock.wait(timeout);
069                } catch (InterruptedException e) {
070                    Thread.currentThread().interrupt();
071                }
072            }
073        }
074        return this.response;
075    }
076
077    /**
078     * close this holder
079     */
080    public void close() {
081        synchronized (lock) {
082            notified = true;
083            lock.notifyAll();
084        }
085    }
086}