forked from mongodb/mongo-java-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDBPortPool.java
More file actions
282 lines (231 loc) · 9.2 KB
/
Copy pathDBPortPool.java
File metadata and controls
282 lines (231 loc) · 9.2 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// DBPortPool.java
/**
* Copyright (C) 2008 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import com.mongodb.util.ConnectionPoolStatisticsBean;
import com.mongodb.util.SimplePool;
import com.mongodb.util.management.JMException;
import com.mongodb.util.management.MBeanServerFactory;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
/**
* This class is NOT part of the public API. Be prepared for non-binary compatible changes in minor releases.
*/
public class DBPortPool extends SimplePool<DBPort> {
public String getHost() {
return _addr.getHost();
}
public int getPort() {
return _addr.getPort();
}
public synchronized ConnectionPoolStatisticsBean getStatistics() {
return new ConnectionPoolStatisticsBean(getTotal(), getInUse(), getInUseConnections());
}
private InUseConnectionBean[] getInUseConnections() {
List<InUseConnectionBean> inUseConnectionInfoList = new ArrayList<InUseConnectionBean>();
long currentNanoTime = System.nanoTime();
for (DBPort port : _out) {
inUseConnectionInfoList.add(new InUseConnectionBean(port, currentNanoTime));
}
return inUseConnectionInfoList.toArray(new InUseConnectionBean[inUseConnectionInfoList.size()]);
}
static class Holder {
Holder( MongoOptions options ){
_options = options;
}
DBPortPool get( ServerAddress addr ){
DBPortPool p = _pools.get( addr );
if (p != null)
return p;
synchronized (_pools) {
p = _pools.get( addr );
if (p != null) {
return p;
}
p = createPool(addr);
_pools.put( addr , p);
try {
String on = createObjectName(addr);
if (MBeanServerFactory.getMBeanServer().isRegistered(on)) {
MBeanServerFactory.getMBeanServer().unregisterMBean(on);
Bytes.LOGGER.log(Level.INFO, "multiple Mongo instances for same host, jmx numbers might be off");
}
MBeanServerFactory.getMBeanServer().registerMBean(p, on);
} catch (JMException e) {
Bytes.LOGGER.log(Level.WARNING, "JMX registration error: " + e +
"\nConsider setting com.mongodb.MongoOptions.alwaysUseMBeans property to true." +
"\nContinuing...");
} catch (java.security.AccessControlException e) {
Bytes.LOGGER.log(Level.WARNING, "JMX registration error: " + e +
"\nContinuing...");
}
}
return p;
}
private DBPortPool createPool(final ServerAddress addr) {
if (isJava5 || _options.isAlwaysUseMBeans()) {
return new Java5MongoConnectionPool(addr, _options);
} else {
return new MongoConnectionPool(addr, _options);
}
}
void close(){
synchronized ( _pools ){
for ( DBPortPool p : _pools.values() ){
p.close();
try {
String on = createObjectName( p._addr );
if ( MBeanServerFactory.getMBeanServer().isRegistered(on) ){
MBeanServerFactory.getMBeanServer().unregisterMBean(on);
}
} catch ( JMException e ){
Bytes.LOGGER.log( Level.WARNING , "jmx de-registration error, continuing" , e );
}
}
}
}
private String createObjectName( ServerAddress addr ) {
String name = "com.mongodb:type=ConnectionPool,host=" + addr.toString().replace( ":" , ",port=" ) + ",instance=" + _serial;
if ( _options.description != null )
name += ",description=" + _options.description;
return name;
}
static {
isJava5 = System.getProperty("java.version").startsWith("1.5");
}
final MongoOptions _options;
final Map<ServerAddress,DBPortPool> _pools = Collections.synchronizedMap( new HashMap<ServerAddress,DBPortPool>() );
final int _serial = nextSerial.incrementAndGet();
// we use this to give each Holder a different mbean name
static AtomicInteger nextSerial = new AtomicInteger(0);
static final boolean isJava5;
}
// ----
public static class NoMoreConnection extends MongoInternalException {
private static final long serialVersionUID = -4415279469780082174L;
NoMoreConnection( String msg ){
super( msg );
}
}
public static class SemaphoresOut extends NoMoreConnection {
private static final long serialVersionUID = -4415279469780082174L;
private static final String message = "Concurrent requests for database connection have exceeded limit";
SemaphoresOut(){
super( message );
}
SemaphoresOut(int numPermits){
super( message + " of " + numPermits);
}
}
public static class ConnectionWaitTimeOut extends NoMoreConnection {
private static final long serialVersionUID = -4415279469780082174L;
ConnectionWaitTimeOut(int timeout) {
super("Connection wait timeout after " + timeout + " ms");
}
}
// ----
DBPortPool( ServerAddress addr , MongoOptions options ){
super( "DBPortPool-" + addr.toString() + ", options = " + options.toString() , options.connectionsPerHost );
_options = options;
_addr = addr;
_waitingSem = new Semaphore( _options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier );
}
protected long memSize( DBPort p ){
return 0;
}
@Override
protected int pick( int recommended, boolean couldCreate ){
int id = System.identityHashCode(Thread.currentThread());
for (int i = _avail.size() - 1; i >= 0; i--){
if ( _avail.get(i)._lastThread == id )
return i;
}
return couldCreate ? -1 : recommended;
}
/**
* @return
* @throws MongoException
*/
@Override
public DBPort get() {
DBPort port = null;
if ( ! _waitingSem.tryAcquire() )
throw new SemaphoresOut(_options.connectionsPerHost * _options.threadsAllowedToBlockForConnectionMultiplier);
try {
port = get( _options.maxWaitTime );
} catch (InterruptedException e) {
throw new MongoInterruptedException(e);
} finally {
_waitingSem.release();
}
if ( port == null )
throw new ConnectionWaitTimeOut( _options.maxWaitTime );
port._lastThread = System.identityHashCode(Thread.currentThread());
return port;
}
// return true if the exception is recoverable
boolean gotError( Exception e ){
if (e instanceof java.nio.channels.ClosedByInterruptException){
// this is probably a request that is taking too long
// so usually doesn't mean there is a real db problem
return true;
}
if ( e instanceof InterruptedIOException){
// we don't want to clear the port pool for a connection timing out or interrupted
return true;
}
Bytes.LOGGER.log( Level.WARNING , "emptying DBPortPool to " + getServerAddress() + " b/c of error" , e );
// force close all sockets
List<DBPort> all = new ArrayList<DBPort>();
while ( true ){
try {
DBPort temp = get(0);
if ( temp == null )
break;
all.add( temp );
} catch (InterruptedException interruptedException) {
throw new MongoInterruptedException(interruptedException);
}
}
for ( DBPort p : all ){
p.close();
done(p);
}
return false;
}
@Override
public void cleanup( DBPort p ){
p.close();
}
@Override
protected DBPort createNew(){
return new DBPort( _addr , this , _options );
}
public ServerAddress getServerAddress() {
return _addr;
}
final MongoOptions _options;
final private Semaphore _waitingSem;
final ServerAddress _addr;
boolean _everWorked = false;
}