What will be the result of the following code compilation and execution?

public class Test {
    private static class Resource {
        public int value;
    };

    private Resource resourceA = new Resource();
    private Resource resourceB = new Resource();

    public int read() {
        synchronized (resourceA) {
            synchronized (resourceB) {
                return resourceA.value + resourceB.value;
            }
        }
    }

    public void write(int a, int b) {
        synchronized (resourceB) {
            synchronized (resourceA) {
                resourceA.value = a;
                resourceB.value = b;
            }
        }
    }

    public static void main(String[] args) {
        final Test test = new Test();

        Runnable targetA = new Runnable() {
            public void run() {
                while (true) 
                    System.out.println(test.read());
            }
        };

        Runnable targetB = new Runnable() {
            public void run() {
                while (true) 
                    test.write(1, 2);
            }
        };

        new Thread(targetA).start();
        new Thread(targetB).start();
    }
}
Explanation
Sooner or later java's thread sheduler will fall into a state when threadA will have a lock on object resourceA (or resourceB), and thread threadB -- a lock on object resourceB (or resourceA). Both threads will be locked and will infinitely wait for objects that they need. This state is called deadlock.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes