Timing Multithreaded Tests

I measured timings of the three Counter classes in the previous section using another class, CounterTest. This timing class illustrates some pitfalls you need to avoid when timing multithreaded applications, so I’ll go into a little detail about the CounterTest definition.

The first naive implementation of CounterTest is quite simple. Just create a Thread subclass with the run() method running timed tests of the classes you are measuring. You need an extra instance variable for the Counter3 class, so the class can be defined as:

package tuning.threads; public class CounterTest extends Thread { //instance variable to specify which thread we are. int num; public CounterTest(int threadnum) { super( ); num = threadnum; } // main forks four threads public static void main(String[] args) { int REPEAT = (args.length > 0) ? Integer.parseInt(args[0]) : 10000000; for (int i = 0; i < 4; i++) (new CounterTest(i)).start( ); } public void run( ) { Counter1.initialize(0); long time = System.currentTimeMillis( ); for (int i = REPEAT; i > 0; i--) Counter1.addAmount(0, 1); System.out.println("Counter1 count: " + Counter1.getAmount(0) + " time: " + (System.currentTimeMillis( )-time)); Counter2.initialize(0); time = System.currentTimeMillis( ); for (int i = REPEAT; i > 0; i--) Counter2.addAmount(0, 1); System.out.println("Counter2 count: " + Counter2.getAmount(0) + " time: " + (System.currentTimeMillis( )-time)); Counter3.initialize(this); time = System.currentTimeMillis( ...

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.