Skip to content

Instantly share code, notes, and snippets.

@dimzon
Created April 3, 2014 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimzon/9958603 to your computer and use it in GitHub Desktop.
Save dimzon/9958603 to your computer and use it in GitHub Desktop.
fast and easy object pool
package ru.narod.dimzon541.utils.pooling;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
public class EasyPool<E> {
private final ConcurrentLinkedQueue<PoolSocket> sockets = new ConcurrentLinkedQueue<>();
private final Semaphore semaphore = new Semaphore(1,true);
public EasyPool(int poolSize) {
for (int i = 0; i < poolSize; i++) {
sockets.offer(new PoolSocket());
}
}
public PoolSocket getSocket() throws InterruptedException {
for(;;){
PoolSocket socket = sockets.poll();
if(socket!=null) return socket;
semaphore.acquire();
}
}
public class PoolSocket implements AutoCloseable{
private E object;
public E getObject() {
return object;
}
public void setObject(E object) {
this.object = object;
}
@Override
public void close() {
sockets.offer(this);
semaphore.release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment