forked from iluwatar/java-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathObjectPool.java
More file actions
37 lines (30 loc) · 766 Bytes
/
ObjectPool.java
File metadata and controls
37 lines (30 loc) · 766 Bytes
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
package com.iluwatar.object.pool;
import java.util.HashSet;
/**
*
* Generic object pool
*
* @param <T>
*/
public abstract class ObjectPool<T> {
private HashSet<T> available = new HashSet<>();
private HashSet<T> inUse = new HashSet<>();
protected abstract T create();
public synchronized T checkOut() {
if (available.size() <= 0) {
available.add(create());
}
T instance = available.iterator().next();
available.remove(instance);
inUse.add(instance);
return instance;
}
public synchronized void checkIn(T instance) {
inUse.remove(instance);
available.add(instance);
}
@Override
public String toString() {
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
}
}