неделя, 16 януари 2011 г.

Why not to use intristic locking

package crap;

public class Deadlock {

    public static void main(String[] args) throws InterruptedException {
        Deadlock deadlock = new Deadlock();
        deadlock.go();
    }

    private void go() throws InterruptedException {
        ImplicitLock lock = new ImplicitLock();
        FooRunnable r1 = new FooRunnable(lock);
        // ExplicitLock lock = new ExplicitLock();
        // FooRunnable r1 = new FooRunnable(lock);

        synchronized (lock) {
            Thread t1 = new Thread(r1);
            t1.start();
            t1.join();
        }
    }

    class ImplicitLock implements Fooable {
        public synchronized void foo() {
            int x = 2;
            x++;
        }
    }

    class ExplicitLock implements Fooable {
        private final Object monitor = new Object();

        public void foo() {
            synchronized (monitor) {
                int x = 2;
                x++;
            }
        }
    }

    interface Fooable {
        void foo();
    }

    class FooRunnable implements Runnable {
        private Fooable fooable;

        public FooRunnable(Fooable fooable) {
            this.fooable = fooable;
        }

        @Override
        public void run() {
            fooable.foo();
        }

    }
}