-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectPool.java
More file actions
27 lines (24 loc) · 913 Bytes
/
ObjectPool.java
File metadata and controls
27 lines (24 loc) · 913 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
import java.util.Queue;
import java.util.LinkedList;
public class ObjectPool {
private final Queue<Reusable> availableObjects = new LinkedList<>();
private int objectCounter = 0;
private final int MAX_POOL_SIZE = 3;
// Retrieves an object from the pool
public Reusable getObject() {
if (availableObjects.isEmpty()) {
if (objectCounter < MAX_POOL_SIZE) {
Reusable newObject = new Reusable(++objectCounter);
return newObject;
} else {
throw new RuntimeException("Max pool size reached. No available objects.");
}
}
return availableObjects.poll();
}
// Returns an object back to the pool
public void releaseObject(Reusable object) {
System.out.println("Reusable object " + object.getId() + " returned to the pool.");
availableObjects.offer(object);
}
}