1 package org.apache.ojb.broker.core; 2 3 17 18 import java.util.Collection ; 19 import java.util.HashMap ; 20 import java.util.HashSet ; 21 import java.util.Iterator ; 22 import java.util.WeakHashMap ; 23 24 import org.apache.ojb.broker.PBFactoryException; 25 import org.apache.ojb.broker.PBKey; 26 import org.apache.ojb.broker.PersistenceBrokerException; 27 import org.apache.ojb.broker.PersistenceBrokerInternal; 28 29 37 public class PersistenceBrokerThreadMapping 38 { 39 45 private static Collection loadedHMs = new HashSet (); 46 47 50 private static ThreadLocal currentBrokerMap = new ThreadLocal (); 51 52 58 public static void setCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker) 59 throws PBFactoryException 60 { 61 HashMap map = (HashMap ) currentBrokerMap.get(); 62 WeakHashMap set = null; 63 if(map == null) 64 { 65 map = new HashMap (); 66 currentBrokerMap.set(map); 67 68 loadedHMs.add(map); 69 } 70 else 71 { 72 set = (WeakHashMap ) map.get(key); 73 } 74 75 if(set == null) 76 { 77 set = new WeakHashMap (); 79 map.put(key, set); 80 } 81 set.put(broker, null); 82 } 83 84 90 public static void unsetCurrentPersistenceBroker(PBKey key, PersistenceBrokerInternal broker) 91 throws PBFactoryException 92 { 93 HashMap map = (HashMap ) currentBrokerMap.get(); 94 WeakHashMap set = null; 95 if(map != null) 96 { 97 set = (WeakHashMap ) map.get(key); 98 if(set != null) 99 { 100 set.remove(broker); 101 if(set.isEmpty()) 102 { 103 map.remove(key); 104 } 105 } 106 if(map.isEmpty()) 107 { 108 currentBrokerMap.set(null); 109 loadedHMs.remove(map); 110 } 111 } 112 } 113 114 121 public static PersistenceBrokerInternal currentPersistenceBroker(PBKey key) 122 throws PBFactoryException, PersistenceBrokerException 123 { 124 HashMap map = (HashMap ) currentBrokerMap.get(); 125 WeakHashMap set; 126 PersistenceBrokerInternal broker = null; 127 128 if(map == null) 129 { 130 return null; 131 } 132 133 set = (WeakHashMap ) map.get(key); 134 if(set == null) 135 { 136 return null; 137 } 138 139 for(Iterator it = set.keySet().iterator(); it.hasNext();) 141 { 142 PersistenceBrokerInternal tmp = (PersistenceBrokerInternal) it.next(); 143 if(tmp == null || tmp.isClosed()) 144 { 145 it.remove(); 146 continue; 147 } 148 broker = tmp; 149 if(tmp.isInTransaction()) 150 { 151 break; } 153 } 154 return broker; 155 } 156 157 161 public static void shutdown() 162 { 163 for(Iterator it = loadedHMs.iterator(); it.hasNext();) 164 { 165 ((HashMap ) it.next()).clear(); 166 } 167 loadedHMs.clear(); 168 loadedHMs = null; 169 currentBrokerMap = null; 170 } 171 } 172 | Popular Tags |