01: // THIS SOFTWARE IS PROVIDED BY SOFTARIS PTY.LTD. AND OTHER METABOSS
02: // CONTRIBUTORS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
03: // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
04: // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOFTARIS PTY.LTD.
05: // OR OTHER METABOSS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
06: // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
07: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
08: // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
09: // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
10: // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
11: // EVEN IF SOFTARIS PTY.LTD. OR OTHER METABOSS CONTRIBUTORS ARE ADVISED OF THE
12: // POSSIBILITY OF SUCH DAMAGE.
13: //
14: // Copyright 2000-2005 © Softaris Pty.Ltd. All Rights Reserved.
15: package com.metaboss.util;
16:
17: import java.util.Collections;
18: import java.util.HashMap;
19: import java.util.Iterator;
20: import java.util.Map;
21:
22: /**
23: * This container can store one object of the certain type per thread
24: * It is designed to encapsulate complexities of the threadsafe storage
25: * It is recommended that storage itself is created in the class constructor
26: * of the class instances of which will use it.
27: *
28: * @version $Revsion: $
29: * @author Rost Vashevnik
30: */
31: public class ThreadSafeStorage {
32: private Map mStorage = Collections.synchronizedMap(new HashMap());
33:
34: /**
35: * Puts an object into the storage
36: * @param pObject - an object to store
37: */
38: public void put(Object pObject) {
39: mStorage.put(Thread.currentThread(), pObject);
40: }
41:
42: /**
43: * Gets an object from the storage
44: * @return Object whatever was stored before or null if nothing stored for this thread
45: */
46: public Object get() {
47: return mStorage.get(Thread.currentThread());
48: }
49:
50: /**
51: * Removes an object from the storage
52: * @return Object whatever was stored before or null if nothing was stored for this thread
53: */
54: public Object remove() {
55: return mStorage.remove(Thread.currentThread());
56: }
57:
58: /**
59: * Removes data object from the storage
60: * @param pObjectToRemove an object to remove
61: * @return Object which was stored or null if nothing was stored for this thread
62: */
63: public Object remove(Object pObjectToRemove) {
64: // Look for the object in synchronized fashion
65: synchronized (mStorage) {
66: Iterator lIter = mStorage.entrySet().iterator();
67: while (lIter.hasNext()) {
68: Map.Entry lEntry = (Map.Entry) lIter.next();
69: if (lEntry.getValue().equals(pObjectToRemove)) {
70: return mStorage.remove(lEntry.getKey());
71: }
72: }
73: }
74: return null;
75: }
76: }
|