-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathObjectPool.java
More file actions
49 lines (41 loc) · 1.02 KB
/
ObjectPool.java
File metadata and controls
49 lines (41 loc) · 1.02 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
package objectpool;
import java.util.HashSet;
import java.util.Set;
/**
* @author nemo
* Generic object pool.
*
* @param <T> Type T of Object in the Pool
*/
public abstract class ObjectPool<T> {
private final Set<T> available = new HashSet<>();
private final Set<T> inUse = new HashSet<>();
protected abstract T create();
/**
* Checkout object from pool.
*/
public synchronized T checkOut() {
if (available.isEmpty()) {
available.add(create());
}
T instance = available.iterator().next();
available.remove(instance);
inUse.add(instance);
return instance;
}
/**
* CheckIN object from pool.
*/
public synchronized void checkIn(T instance) {
inUse.remove(instance);
available.add(instance);
}
@Override
public synchronized String toString() {
return String.format(
"Pool available = %d inUse = %d",
available.size(),
inUse.size()
);
}
}