Skip to content

Instantly share code, notes, and snippets.

@miniway
Created November 18, 2015 00:04
Show Gist options
  • Save miniway/85d1592d1db1bad1ac26 to your computer and use it in GitHub Desktop.
Save miniway/85d1592d1db1bad1ac26 to your computer and use it in GitHub Desktop.
test case
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;
public class Main
{
public static class ResourcePoolNew
extends ResourcePool<Object> {
public ResourcePoolNew(int maxCapacity)
{
super(maxCapacity);
}
@Override
public void close() {}
@Override
protected Object createNewResource()
{
return new Object();
}
}
public static class ResourcePoolOld
extends ResourcePoolOrg<Object> {
public ResourcePoolOld(int maxCapacity)
{
super(maxCapacity);
}
@Override
public void close() {}
@Override
protected Object createNewResource()
{
return new Object();
}
}
private static long test(String name, final PoolBase<Object> pool)
{
ExecutorService executor = Executors.newFixedThreadPool(1000);
final AtomicLong elapsed = new AtomicLong();
for (int i = 0; i < 10000000; i++) {
final int load = i % 100;
executor.execute(new Runnable()
{
public void run()
{
long startTime = System.nanoTime();
Object value = pool.acquire();
elapsed.addAndGet(System.nanoTime() - startTime);
LockSupport.parkNanos(load); // simulate work load
pool.release(value);
}
});
try {
if (i % 100 == 0) Thread.sleep(1);
}
catch (InterruptedException e) {
}
}
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.DAYS);
}
catch (InterruptedException e) {
}
System.out.println(name + " Elapsed " + elapsed.get());
return elapsed.get();
}
public static void main(String[] args) {
int count = 10;
long elapsed = 0;
String name = args[0];
int poolSize = Integer.parseInt(args[1]);
for (int i = 0; i < count + 1; i++) {
if (name.equals("old")) {
elapsed += test(name, new ResourcePoolOld(poolSize));
}
else {
elapsed += test(name, new ResourcePoolNew(poolSize));
}
if (i == 0) elapsed = 0; // exclude warm up
}
System.out.println("Average Ealpsed " + elapsed / count);
}
}
> old 1000 # resource is not full
=> Average Ealpsed 4106731000 (ns)
> new 1000
=> Average Ealpsed 1306103500 # 3 times faster
> old 10 # resource is full, blocking wait
=> Average Ealpsed 9752953800
> new 10
=> Average Ealpsed 5322552400 # 1.8 times faster
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment