Created
April 14, 2014 18:35
-
-
Save chrisvest/10672412 to your computer and use it in GitHub Desktop.
Benchmarking a SynchronousQueue with JMH. Enjoy.
This file contains 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
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