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     */
017    package org.apache.activemq.transport.tcp;
018    
019    import org.apache.activemq.command.Response;
020    
021    /**
022     * ResponseHolder utility
023     * 
024     * 
025     */
026    public class ResponseHolder {
027        protected Response response;
028        protected Object lock = new Object();
029        protected boolean notified;
030    
031        /**
032         * Construct a receipt holder
033         */
034        public ResponseHolder() {
035        }
036    
037        /**
038         * Set the Response for this holder
039         * 
040         * @param r
041         */
042        public void setResponse(Response r) {
043            synchronized (lock) {
044                this.response = r;
045                notified = true;
046                lock.notify();
047            }
048        }
049    
050        /**
051         * Get the Response
052         * 
053         * @return the Response or null if it is closed
054         */
055        public Response getResponse() {
056            return getResponse(0);
057        }
058    
059        /**
060         * wait upto <Code>timeout</Code> timeout ms to get a receipt
061         * 
062         * @param timeout
063         * @return
064         */
065        public Response getResponse(int timeout) {
066            synchronized (lock) {
067                if (!notified) {
068                    try {
069                        lock.wait(timeout);
070                    } catch (InterruptedException e) {
071                        Thread.currentThread().interrupt();
072                    }
073                }
074            }
075            return this.response;
076        }
077    
078        /**
079         * close this holder
080         */
081        public void close() {
082            synchronized (lock) {
083                notified = true;
084                lock.notifyAll();
085            }
086        }
087    }