|
1 /* |
|
2 * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). |
|
3 * All rights reserved. |
|
4 * This component and the accompanying materials are made available |
|
5 * under the terms of the License "Eclipse Public License v1.0" |
|
6 * which accompanies this distribution, and is available |
|
7 * at the URL "http://www.eclipse.org/legal/epl-v10.html". |
|
8 * |
|
9 * Initial Contributors: |
|
10 * Nokia Corporation - initial contribution. |
|
11 * |
|
12 * Contributors: |
|
13 * |
|
14 * Description: |
|
15 * |
|
16 */ |
|
17 |
|
18 package com.nokia.carbide.cpp.pi.util; |
|
19 // import for com.nokai.sdt.utils |
|
20 //package com.nokia.sdt.utils; |
|
21 |
|
22 import java.util.HashMap; |
|
23 import java.util.Iterator; |
|
24 import java.util.Map; |
|
25 import java.util.Set; |
|
26 |
|
27 import org.eclipse.swt.graphics.Resource; |
|
28 |
|
29 /** |
|
30 * Map-like class for managing disposable objects. |
|
31 * <p> |
|
32 * Entries are accessed via keys. When the map is |
|
33 * released, all entries are released. If entries |
|
34 * implement IDisposable or like interfaces, we call |
|
35 * their dispose() methods. Null values are not allowed. |
|
36 */ |
|
37 public class CacheMap<K,V> implements IDisposable { |
|
38 |
|
39 private Map<Object,Object> map = new HashMap<Object,Object> (); |
|
40 |
|
41 public Set keySet() { |
|
42 return map.keySet(); |
|
43 } |
|
44 |
|
45 public void put(Object key, Object value) { |
|
46 //Check.checkArg(value); |
|
47 synchronized(map) { |
|
48 map.put(key, value); |
|
49 } |
|
50 } |
|
51 |
|
52 public Object get(Object key) { |
|
53 Object result; |
|
54 synchronized(map) { |
|
55 result = map.get(key); |
|
56 } |
|
57 return result; |
|
58 } |
|
59 |
|
60 public void remove(Object key) { |
|
61 synchronized(map) { |
|
62 map.remove(key); |
|
63 } |
|
64 } |
|
65 |
|
66 public void dispose() { |
|
67 if (map != null) { |
|
68 // object should no longer be used after IDisposable.dispose |
|
69 disposeAll(); |
|
70 map = null; |
|
71 } |
|
72 } |
|
73 |
|
74 private void disposeObject(Object value) { |
|
75 if (value instanceof IDisposable) { |
|
76 IDisposable disposable = (IDisposable) value; |
|
77 disposable.dispose(); |
|
78 } |
|
79 else if (value instanceof Resource) { |
|
80 Resource r = (Resource) value; |
|
81 r.dispose(); |
|
82 } |
|
83 } |
|
84 |
|
85 public void disposeItem(Object key) { |
|
86 Object item; |
|
87 synchronized(map) { |
|
88 item = map.remove(key); |
|
89 } |
|
90 if (item != null) |
|
91 disposeObject(item); |
|
92 } |
|
93 |
|
94 public void disposeAll() { |
|
95 synchronized(map) { |
|
96 for (Iterator iter = map.values().iterator(); iter.hasNext();) { |
|
97 Object element = iter.next(); |
|
98 disposeObject(element); |
|
99 } |
|
100 map.clear(); |
|
101 } |
|
102 } |
|
103 |
|
104 public int size() { |
|
105 return map.size(); |
|
106 } |
|
107 } |
|
108 |