1 21 22 package com.rift.coad.util.connection; 24 25 import java.util.Map ; 27 import java.util.HashMap ; 28 import java.util.concurrent.ConcurrentHashMap ; 29 import javax.naming.Context ; 30 import javax.naming.InitialContext ; 31 32 import org.apache.log4j.Logger; 34 35 36 43 public class ConnectionManager { 44 45 private static ConnectionManager singleton = null; 47 private static Map singletonMap = new ConcurrentHashMap (); 48 49 protected static Logger log = 51 Logger.getLogger(ConnectionManager.class.getName()); 52 53 54 private Context context = null; 56 private Map lookupCache = new ConcurrentHashMap (); 57 private Map synchKeyCache = new HashMap (); 58 59 62 private ConnectionManager() throws ConnectionException { 63 try { 64 context = new InitialContext (); 65 } catch (Exception ex) { 66 log.error("Failed init the connection manager : " + ex.getMessage(), 67 ex); 68 } 69 } 70 71 72 77 private ConnectionManager(Context context) { 78 this.context = context; 79 } 80 81 82 89 public synchronized static ConnectionManager getInstance() throws 90 ConnectionException { 91 if (singleton == null) { 92 singleton = new ConnectionManager(); 93 } 94 return singleton; 95 } 96 97 98 105 public static ConnectionManager getInstance(Context context) throws 106 ConnectionException { 107 synchronized (context) { 108 if (!singletonMap.containsKey(context)) { 109 singletonMap.put(context,new ConnectionManager()); 110 } 111 return (ConnectionManager)singletonMap.get(context); 112 } 113 } 114 115 116 124 public Object getConnection(Class type, String jndiURL) throws 125 ConnectionException, java.lang.ClassCastException { 126 Object syncEntry = getSyncKey(jndiURL); 127 synchronized(syncEntry) { 128 Connection connection = (Connection)lookupCache.get(jndiURL); 129 if (connection == null) { 130 if (RMIConnection.isRMIConnection(jndiURL)) { 131 connection = new RMIConnection(context, jndiURL); 132 } else { 133 connection = new ProxyConnection(context, jndiURL); 134 } 135 lookupCache.put(jndiURL,connection); 136 } 137 return connection.getConnection(type); 138 } 139 } 140 141 142 148 private synchronized Object getSyncKey(String name) { 149 Object entry = synchKeyCache.get(name); 150 if (entry != null) { 151 return entry; 152 } 153 entry = new String (name); 154 synchKeyCache.put(name,entry); 155 return entry; 156 } 157 } 158 | Popular Tags |