Skip to content

Instantly share code, notes, and snippets.

@yawnt
Created July 17, 2017 14:16
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 yawnt/c6fb8fee2b9d151449fb88eb77be534b to your computer and use it in GitHub Desktop.
Save yawnt/c6fb8fee2b9d151449fb88eb77be534b to your computer and use it in GitHub Desktop.
import static java.lang.System.out;
public class InterThreadLatency
{
private static final int REPETITIONS = 100 * 1000 * 1000;
private static volatile int ping = -1;
private static volatile int pong = -1;
public static void main(final String[] args)
throws Exception
{
for (int i = 0; i < 5; i++)
{
final long duration = runTest();
out.printf("%d - %dns avg latency - ping=%d pong=%d\n",
i,
duration / (REPETITIONS * 2),
ping,
pong);
}
}
private static long runTest() throws InterruptedException
{
final Thread pongThread = new Thread(new PongRunner());
final Thread pingThread = new Thread(new PingRunner());
pongThread.start();
pingThread.start();
final long start = System.nanoTime();
pongThread.join();
return System.nanoTime() - start;
}
public static class PingRunner implements Runnable
{
public void run()
{
for (int i = 0; i < REPETITIONS; i++)
{
ping = i;
while (i != pong)
{
// busy spin
}
}
}
}
public static class PongRunner implements Runnable
{
public void run()
{
for (int i = 0; i < REPETITIONS; i++)
{
while (i != ping)
{
// busy spin
}
pong = i;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment