Created
July 11, 2019 14:55
-
-
Save athlan/3ff85fe0e9ebd3f47cdd9d96850e606d to your computer and use it in GitHub Desktop.
Java Object Pool
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package pl.athlan.commons.pool; | |
import static java.util.stream.Collectors.toList; | |
import java.util.Collection; | |
import java.util.concurrent.ArrayBlockingQueue; | |
import java.util.concurrent.BlockingQueue; | |
import java.util.function.Supplier; | |
import java.util.stream.IntStream; | |
import javax.annotation.concurrent.ThreadSafe; | |
import lombok.SneakyThrows; | |
@ThreadSafe | |
public interface ObjectPool<T> { | |
static <T> ObjectPool<T> createObjectPool( | |
int numberOfObjects, | |
Supplier<T> objectFactory) { | |
return new ArrayBlockingQueueObjectPool<>(numberOfObjects, objectFactory); | |
} | |
T borrowObject(); | |
void returnObject(T borrowed); | |
class ArrayBlockingQueueObjectPool<T> implements ObjectPool<T> { | |
private final BlockingQueue<T> bench; | |
private ArrayBlockingQueueObjectPool( | |
int numberOfObjects, | |
Supplier<T> objectFactory) { | |
bench = new ArrayBlockingQueue<>(numberOfObjects, true, createObjectsCollection(numberOfObjects, objectFactory)); | |
} | |
private Collection<T> createObjectsCollection( | |
int numberOfObjects, | |
Supplier<T> objectFactory) { | |
return IntStream.range(1, numberOfObjects) | |
.mapToObj(i -> objectFactory.get()) | |
.collect(toList()); | |
} | |
@SneakyThrows | |
public T borrowObject() { | |
return bench.take(); | |
} | |
public void returnObject(T borrowed) { | |
bench.offer(borrowed); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment