Java synchronized instance member doesn't work in a nested way

Michael Wang :

When programming with Java synchronized, I happend to find a usage which doesn't work as I expect. That is, in thread A, it accesses instance member (content) inside two nested synchronized blocks:

synchronized(this){
    synchronized (content) {content = str;}
}

while in thread B, it accesses the same content in only one synchronized block:

synchronized (content) {content = str;}

I expected this can work as a normal usage of

synchronized (content) {content = str;}

however, it doesn't. It works as there is no synchronized. The complete code and logs are as following:

public class JavaSync {
    public static void main(String[] args) {
        SyncContent syncContent = new SyncContent("JavaSync");

        ThreadA a = new ThreadA(syncContent);
        a.setName("A");
        a.start();

        ThreadB b = new ThreadB(syncContent);
        b.setName("B");
        b.start();

        ThreadC c = new ThreadC(syncContent);
        c.setName("C");
        c.start();
    }
}

class SyncContent {
    volatile String content = new String();

    public SyncContent(String content) {
        this.content = content;
    }

    private double timeConsuming() {
        double a, b, c;
        double sum = 0;
        for (int i = 1; i < 2000000; i++) {
            a = i + sum / ( i * 19);
            b = a / 17;
            c = b * 23;
            sum += (b + c - a) / (a + i);
        }
        return sum;
    }

    synchronized public void syncFunc(String str) {
        System.out.println("syncFunc.Thread: " + Thread.currentThread().getName() + " enter: " + System.currentTimeMillis());
        synchronized (content) {
            System.out.println("syncFunc.Thread: " + Thread.currentThread().getName() + " content old: " + content);
            content = str;
            System.out.println("syncFunc.Thread: " + Thread.currentThread().getName() + " content new: " + content);
            //Thread.sleep(2000);  // InterruptedException
            System.out.println("syncFunc.Thread: dummy result: " + timeConsuming());
            System.out.println("syncFunc.Thread: " + Thread.currentThread().getName() + " content final: " + content);
        }
        System.out.println("syncFunc.Thread: " + Thread.currentThread().getName() + " exit: " + System.currentTimeMillis());
        /*try {
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    public void syncThis(String str) {
        synchronized(this) {
            System.out.println("syncThis.Thread: " + Thread.currentThread().getName() + " enter: " + System.currentTimeMillis());
            synchronized (content) {
                System.out.println("syncThis.Thread: " + Thread.currentThread().getName() + " content old: " + content);
                content = str;
                System.out.println("syncThis.Thread: " + Thread.currentThread().getName() + " content new: " + content);
                //Thread.sleep(2000);  // InterruptedException
                System.out.println("syncThis.Thread: dummy result: " + timeConsuming());
                System.out.println("syncThis.Thread: " + Thread.currentThread().getName() + " content final: " + content);
            }
            System.out.println("syncThis.Thread: " + Thread.currentThread().getName() + " exit: " + System.currentTimeMillis());
            /*try {
            } catch (Exception e) {
                e.printStackTrace();
            }*/
        }
    }

    public void syncVariable(String str) {
        synchronized(content) {
            System.out.println("syncVariable.Thread: " + Thread.currentThread().getName() + " enter: " + System.currentTimeMillis());
            System.out.println("syncVariable.Thread: " + Thread.currentThread().getName() + " content old: " + content);
            content = str;
            System.out.println("syncVariable.Thread: " + Thread.currentThread().getName() + " content new: " + content);
            System.out.println("syncVariable.Thread: " + Thread.currentThread().getName() + " exit: " + System.currentTimeMillis());
        }
    }
}

class ThreadA extends Thread {
    private SyncContent syncContent;
    private String me = "ThreadA";

    public ThreadA(SyncContent syncContent) {
        super();
        this.syncContent = syncContent;
    }

    @Override
    public void run() {
        syncContent.syncThis(me);
    }
}


class ThreadB extends Thread {
    private SyncContent syncContent;
    private String me = "ThreadB";

    public ThreadB(SyncContent syncContent) {
        super();
        this.syncContent = syncContent;
    }

    @Override
    public void run() {
        syncContent.syncFunc(me);
    }
}

class ThreadC extends Thread {
    private SyncContent syncContent;
    private String me = "ThreadC";

    public ThreadC(SyncContent syncContent) {
        super();
        this.syncContent = syncContent;
    }

    @Override
    public void run() {
        syncContent.syncVariable(me);
    }
}

Logs:

syncThis.Thread: A enter: 1542076529822
syncThis.Thread: A content old: JavaSync
syncThis.Thread: A content new: ThreadA
syncVariable.Thread: C enter: 1542076529823
syncVariable.Thread: C content old: ThreadA
syncVariable.Thread: C content new: ThreadC
syncVariable.Thread: C exit: 1542076529824
syncThis.Thread: dummy result: 411764.5149938948
syncThis.Thread: A content final: ThreadC
syncThis.Thread: A exit: 1542076529862
syncFunc.Thread: B enter: 1542076529862
syncFunc.Thread: B content old: ThreadC
syncFunc.Thread: B content new: ThreadB
syncFunc.Thread: dummy result: 411764.5149938948
syncFunc.Thread: B content final: ThreadB
syncFunc.Thread: B exit: 1542076529897

Why doesn't this happen?

Mureinik :

synchronized applies to an object, not a name of a variable. You enter the synchronized block by locking content, but then in the block, you assign a different object to it. The next time you try to synchronize content you'll be synchronizing different object, so the previously held lock won't interfere with it.

If you use a mutable object, such as a StringBuilder and change its data instead, you'll see the behavior you expect:

synchronized (content) {
    content.setLength(0); // Remove the old content
    content.append(str); // Set the new content
    // Rest of the code...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=90457&siteId=1