FileDocCategorySizeDatePackage
AtomicTest.javaAPI DocExample1990Thu Mar 11 00:02:36 GMT 2004javathreads.examples.ch14

AtomicTest

public class AtomicTest extends Object

Fields Summary
static int
nLoops
static int
nThreads
Constructors Summary
Methods Summary
static voidcleanGC()

        System.gc();
        System.runFinalization();
        System.gc();
    
static voiddoTest(java.lang.Runnable r)

	Thread threads[] = new Thread[nThreads];
	for (int i = 0; i < nThreads; i++) {
	    threads[i] = new Thread(r);
	}
	for (int i = 0; i < nThreads; i++) {
	    threads[i].start();
	}
	for (int i = 0; i < nThreads; i++) {
	    try {
	        threads[i].join();
	    } catch (InterruptedException ie) {}
	}
    
public static voidmain(java.lang.String[] args)


	nLoops = 10000;
	nThreads = 1;
        doTest(new AtomicRunnable());
        doTest(new SyncRunnable());
	nLoops = Integer.parseInt(args[0]);
	nThreads = Integer.parseInt(args[1]);

        System.out.println("Starting atomic test");
	cleanGC();
	Timestamp atomicTS = new Timestamp();
        doTest(new AtomicRunnable());
	atomicTS.stop();
        System.out.println("Atomic took " + atomicTS);

        System.out.println("Starting sync test");
	cleanGC();
	Timestamp syncTS = new Timestamp();
        doTest(new SyncRunnable());
	syncTS.stop();
        System.out.println("Local sync took " + syncTS);

	double d = ((double) (syncTS.elapsedTime() - atomicTS.elapsedTime())) /
		(nLoops * nThreads);
	System.out.println("Atomic operation saves " + d + " " + syncTS.units() + " per call");