What happens if the synchronization variable is reassigned to java?

What happens in the following code? Does synchronization work? This is an interview question.

class T
{
    public static void main(String args[])
    {
        Object myObject = new Object();
        synchronized (myObject)
        {
            myObject = new Object();
        } // end sync
    }
}
+5
source share
6 answers

Each time you enter a synchronized block, you synchronize on another object. Most of the time this will do nothing but confuse you, but there is a small chance that two threads will see the same object and wait.

For this reason, any code analyzers will give you a warning if you synchronize a field that is not final.

+4
source

- , , , myObject ( , , ) .

, (, , ), . , /, , . .

+1

, . , , myObject. , myObject !

, myObject , , . . .

0

, Object . .

0

myObject, , , .

. . , .

0

Run the code AND analyze the result.

public class Test {
    static Foo o = new Foo(0);
    static class Foo {
        private int i = 0;
        Foo(int i) {
            this.i = i;
        }
        public void addOnce() {
            this.i++;
        }
        public String toString() {
            return String.valueOf(i);
        }
    }
    public static void main(String args[]) {
        test1();
        try {Thread.sleep(10000);} catch (Exception e) {}
        test2();
    }
    public static void test1() {
        Runnable r = new Runnable() {
            public void run() {
                synchronized (o) {
                    System.out.println("1------>"+o);
                    o = new Foo(1);
                    try {Thread.sleep(3000);} catch (Exception e) {}
                    System.out.println("1------>"+o);
                }
            }
        };
        new Thread(r).start();
        new Thread(r).start();
    }
    public static void test2() {
        Runnable r = new Runnable() {
            public void run() {
                synchronized (o) {
                    System.out.println("2------>"+o);
                    o.addOnce();
                    try {Thread.sleep(3000);} catch (Exception e) {}
                    System.out.println("2------>"+o);
                }
            }
        };
        new Thread(r).start();
        new Thread(r).start();
    }
}
0
source

All Articles