1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.util.concurrent.atomic.AtomicBoolean;
19 import java.util.concurrent.atomic.AtomicLong;
20
21 import org.jboss.netty.logging.InternalLogger;
22 import org.jboss.netty.logging.InternalLoggerFactory;
23
24
25
26
27
28
29
30
31 public class SharedResourceMisuseDetector {
32
33 private static final int MAX_ACTIVE_INSTANCES = 256;
34 private static final InternalLogger logger =
35 InternalLoggerFactory.getInstance(SharedResourceMisuseDetector.class);
36
37 private final Class<?> type;
38 private final AtomicLong activeInstances = new AtomicLong();
39 private final AtomicBoolean logged = new AtomicBoolean();
40
41 public SharedResourceMisuseDetector(Class<?> type) {
42 if (type == null) {
43 throw new NullPointerException("type");
44 }
45 this.type = type;
46 }
47
48 public void increase() {
49 if (activeInstances.incrementAndGet() > MAX_ACTIVE_INSTANCES) {
50 if (logged.compareAndSet(false, true)) {
51 logger.warn(
52 "You are creating too many " + type.getSimpleName() +
53 " instances. " + type.getSimpleName() +
54 " is a shared resource that must be reused across the" +
55 " application, so that only a few instances are created.");
56 }
57 }
58 }
59
60 public void decrease() {
61 activeInstances.decrementAndGet();
62 }
63 }