Created
October 2, 2015 06:00
-
-
Save brettwooldridge/ddd54c84e5822ba9a0e8 to your computer and use it in GitHub Desktop.
JMH Benchmark to measure thread launch time overhead
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 com.zaxxer.miscmicro; | |
import java.util.concurrent.TimeUnit; | |
import org.openjdk.jmh.annotations.Benchmark; | |
import org.openjdk.jmh.annotations.BenchmarkMode; | |
import org.openjdk.jmh.annotations.Level; | |
import org.openjdk.jmh.annotations.Measurement; | |
import org.openjdk.jmh.annotations.Mode; | |
import org.openjdk.jmh.annotations.OutputTimeUnit; | |
import org.openjdk.jmh.annotations.Scope; | |
import org.openjdk.jmh.annotations.Setup; | |
import org.openjdk.jmh.annotations.State; | |
import sun.misc.Unsafe; | |
@BenchmarkMode(Mode.Throughput) | |
@OutputTimeUnit(TimeUnit.MILLISECONDS) | |
@Measurement(time = 2) | |
@State(Scope.Benchmark) | |
public class ThreadStartMicro | |
{ | |
private static final Unsafe UNSAFE = UnsafeHelper.getUnsafe(); | |
private volatile Thread benchThread; | |
@Setup(Level.Iteration) | |
public void startup() | |
{ | |
benchThread = Thread.currentThread(); | |
} | |
@Benchmark | |
public long threadStart() throws InterruptedException | |
{ | |
MyThread t = new MyThread(); | |
t.start(); | |
if (!t.isStarted()) | |
{ | |
UNSAFE.park(false, TimeUnit.MILLISECONDS.toNanos(200)); | |
} | |
return t.getId(); | |
} | |
private class MyThread extends Thread | |
{ | |
private volatile boolean started; | |
public void run() { | |
started = true; | |
UNSAFE.unpark(benchThread); | |
}; | |
public boolean isStarted() | |
{ | |
return started; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment