4.3. Use atomic variables and locks - Source Code

Code:

package c4.s3;

/**
 * @author Mikalai Zaikin
 */
public class CASCounter {

    private SimulatedCAS value = new SimulatedCAS(); // starts with 0

    public int getValue() {
        return value.getValue();
    }

    public int increment() {
        int oldValue = value.getValue();
        while (value.compareAndSwap(oldValue, oldValue + 1) != oldValue) {
            oldValue = value.getValue();
        }
        return oldValue + 1;
    }
}
					

package c4.s3;

/**
 * @author Mikalai Zaikin
 */
public class Counter1 {

    private int count = 0;

    public int inc() {
        synchronized (this) {
            return ++count;
        }
    }
}

					

package c4.s3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Mikalai Zaikin
 */
public class Counter2 {

    private Lock lock = new ReentrantLock();

    private int count = 0;

    public int inc() {
        lock.lock();
        try {
            int newCount = ++count;
            return newCount;
        } finally {
            lock.unlock();
        }
    }
}
					

package c4.s3;

/**
 * @author Mikalai Zaikin
 */
public class SimulatedCAS {

    private int value;

    public synchronized int getValue() {
        return value;
    }

    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (value == expectedValue) {
            value = newValue;
        }
        return oldValue;
    }
}
					


package c4.s3;

/**
 * @author Mikalai Zaikin
 */
class MyRunnable implements Runnable {
    public CASCounter g;
    public int total = 0;

    MyRunnable(CASCounter g) {
        this.g = g;
    }

    public void run() {
        for (int i=0; i < 10000; i++) {
            synchronized(g) {
            g.increment();
            total += g.getValue();
            }
        }

    }
}
public class Test {

    public static void main(String... s) throws InterruptedException {
        CASCounter g3 = new CASCounter();
        MyRunnable r1 = new MyRunnable(g3);
        MyRunnable r2 = new MyRunnable(g3);
        Thread t1 = new Thread(r1);
        t1.start();
        Thread t2 = new Thread(r2);
        t2.start();
        t1.join();
        t2.join();
        System.out.println(r1.total + r2.total);
    }
}

					

output:

200010000
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide