01 /*
02 *
03 * Licensed to the Apache Software Foundation (ASF) under one
04 * or more contributor license agreements. See the NOTICE file
05 * distributed with this work for additional information
06 * regarding copyright ownership. The ASF licenses this file
07 * to you under the Apache License, Version 2.0 (the
08 * "License"); you may not use this file except in compliance
09 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21 package org.apache.qpid.client;
22
23 import javax.jms.IllegalStateException;
24 import javax.jms.JMSException;
25
26 import java.util.concurrent.atomic.AtomicBoolean;
27
28 /**
29 * Captures the 'closed' state of an object, that is initially open, can be tested to see if it is closed, and provides
30 * a 'close' method to close it.
31 *
32 * <p/><table id="crc"><caption>CRC Card</caption>
33 * <tr><th> Responsibilities <th> Collaborations
34 * <tr><td> Mark an object as closed.
35 * <tr><td> Check if an object is closed.
36 * <tr><td> Raise a JMS exception if an object is closed.
37 * </table>
38 *
39 * @todo Might be better to make this an interface. This whole class doesn't really encapsulate a terribly neat
40 * piece of re-usable functionality. A simple interface defining a close method would suffice.
41 *
42 * @todo The convenience method {@link #checkNotClosed} is not that helpfull, what if the caller wants to do something
43 * other than throw an exception? It doesn't really represent a very usefull re-usable piece of code. Consider
44 * inlining it and dropping the method.
45 */
46 public abstract class Closeable
47 {
48 /**
49 * We use an atomic boolean so that we do not have to synchronized access to this flag. Synchronizing access to this
50 * flag would mean have a synchronized block in every method.
51 */
52 protected final AtomicBoolean _closed = new AtomicBoolean(false);
53
54 /**
55 * Checks if this is closed, and raises a JMSException if it is.
56 *
57 * @throws JMSException If this is closed.
58 */
59 protected void checkNotClosed() throws JMSException
60 {
61 if (isClosed())
62 {
63 throw new IllegalStateException("Object " + toString() + " has been closed");
64 }
65 }
66
67 /**
68 * Checks if this is closed.
69 *
70 * @return <tt>true</tt> if this is closed, <tt>false</tt> otherwise.
71 */
72 public boolean isClosed()
73 {
74 return _closed.get();
75 }
76
77 /**
78 * Closes this object.
79 *
80 * @throws JMSException If this cannot be closed for any reason.
81 */
82 public abstract void close() throws JMSException;
83 }
|