Skip to content

Instantly share code, notes, and snippets.

@chrisvest
Created April 14, 2014 18:35
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 chrisvest/10672412 to your computer and use it in GitHub Desktop.
Save chrisvest/10672412 to your computer and use it in GitHub Desktop.
Benchmarking a SynchronousQueue with JMH. Enjoy.
import java.util.concurrent.SynchronousQueue;
import org.openjdk.jmh.annotations.GenerateMicroBenchmark;
import org.openjdk.jmh.annotations.Group;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.logic.Control;
@State( Scope.Benchmark )
public class BenchmarkSynchronousQueue
{
public static final Object TOKEN = new Object();
private SynchronousQueue<Object> queue;
@Setup
public void createQueue()
{
queue = new SynchronousQueue<Object>();
}
@GenerateMicroBenchmark
@Group("a")
@GroupThreads(1)
public void put()
{
try
{
queue.put( TOKEN );
}
catch ( InterruptedException e )
{
}
}
@GenerateMicroBenchmark
@Group("a")
@GroupThreads(1)
public Object take()
{
try
{
return queue.take();
}
catch ( InterruptedException e )
{
}
return null;
}
@GenerateMicroBenchmark
@Group("a")
@GroupThreads(1)
public void terminationControl(Control control) throws InterruptedException
{
if (control.stopMeasurement)
{
Thread currentThread = Thread.currentThread();
int insistence = 0;
int threadsInPreTearDown;
int workerThreads;
do {
threadsInPreTearDown = 0;
workerThreads = 0;
Thread[] threads = new Thread[Thread.activeCount()];
int count = Thread.enumerate( threads );
for ( int i = 0; i < count; i++ )
{
Thread thread = threads[i];
if (thread == currentThread)
{
continue;
}
if (thread.getName().contains( "worker" ))
{
workerThreads++;
// We do this join to decrease the probability of observing a
// benchmark method, that then moves into the preTearDown by
// the time we interrupt it.
thread.join( 20 );
StackTraceElement[] stackTrace = thread.getStackTrace();
boolean isInTearDown = false;
for (StackTraceElement element : stackTrace)
{
if (element.getMethodName().equals( "preTearDown" ))
{
threadsInPreTearDown++;
isInTearDown = true;
break;
}
}
if (!isInTearDown)
{
thread.interrupt();
}
}
}
} while (threadsInPreTearDown < workerThreads || insistence++ < 3);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment