-
Notifications
You must be signed in to change notification settings - Fork 897
Expand file tree
/
Copy pathConnectionPool.java
More file actions
81 lines (72 loc) · 2.71 KB
/
ConnectionPool.java
File metadata and controls
81 lines (72 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package org.csource.fastdfs.pool;
import org.csource.common.MyException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConnectionPool {
/**
* key is ip:port, value is ConnectionManager
*/
private final static ConcurrentHashMap<String, ConnectionManager> CP = new ConcurrentHashMap<String, ConnectionManager>();
public static Connection getConnection(InetSocketAddress socketAddress) throws IOException {
if (socketAddress == null) {
return null;
}
String key = getKey(socketAddress);
ConnectionManager connectionManager;
connectionManager = CP.get(key);
if (connectionManager == null) {
synchronized (ConnectionPool.class) {
connectionManager = CP.get(key);
if (connectionManager == null) {
connectionManager = new ConnectionManager(socketAddress);
CP.put(key, connectionManager);
}
}
}
return connectionManager.getConnection();
}
public static void releaseConnection(Connection connection) throws IOException {
if (connection == null) {
return;
}
String key = getKey(connection.getInetSocketAddress());
ConnectionManager connectionManager = CP.get(key);
if (connectionManager != null) {
connectionManager.releaseConnection(connection);
} else {
connection.closeDirectly();
}
}
public static void closeConnection(Connection connection) throws IOException {
if (connection == null) {
return;
}
String key = getKey(connection.getInetSocketAddress());
ConnectionManager connectionManager = CP.get(key);
if (connectionManager != null) {
connectionManager.closeConnection(connection);
connectionManager.setActiveTestFlag();
} else {
connection.closeDirectly();
}
}
private static String getKey(InetSocketAddress socketAddress) {
if (socketAddress == null) {
return null;
}
return String.format("%s:%s", socketAddress.getAddress().getHostAddress(), socketAddress.getPort());
}
@Override
public String toString() {
if (!CP.isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, ConnectionManager> managerEntry : CP.entrySet()) {
builder.append("key:[" + managerEntry.getKey() + " ]-------- entry:" + managerEntry.getValue() + "\n");
}
return builder.toString();
}
return null;
}
}