001    /** 
002     * 
003     * Copyright 2004 Protique Ltd
004     * 
005     * Licensed under the Apache License, Version 2.0 (the "License"); 
006     * you may not use this file except in compliance with the License. 
007     * 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     **/
018    package org.activemq.message;
019    
020    /**
021     * ReceiptHolder is a utility class used for waiting for receipts from Packets sent to the broker
022     * 
023     * @version $Revision: 1.1.1.1 $
024     */
025    public class ReceiptHolder {
026        protected Receipt receipt;
027        protected Object lock = new Object();
028        protected boolean notified;
029    
030        /**
031         * Construct a receipt holder
032         */
033        public ReceiptHolder() {
034        }
035    
036        /**
037         * Set the Receipt for this holder
038         *
039         * @param r
040         */
041        public void setReceipt(Receipt r) {
042            synchronized (lock) {
043                this.receipt = r;
044                notified = true;
045                lock.notify();
046            }
047        }
048    
049        /**
050         * Get the Receipt
051         * 
052         * @return the Receipt or null if it is closed
053         */
054        public Receipt getReceipt() {
055            return getReceipt(0);
056        }
057    
058        /**
059         * wait upto <Code>timeout</Code> timeout ms to get a receipt
060         *
061         * @param timeout
062         * @return
063         */
064        public Receipt getReceipt(int timeout) {
065            synchronized (lock) {
066                if (!notified) {
067                    try {
068                        lock.wait(timeout);
069                    }
070                    catch (InterruptedException e) {
071                        e.printStackTrace();
072                    }
073                }
074            }
075            return this.receipt;
076        }
077    
078        /**
079         * close this holder
080         */
081        public void close() {
082            synchronized (lock) {
083                notified = true;
084                lock.notifyAll();
085            }
086        }
087    }