Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

java - Locking on Strings

2 Questions:

  1. str field is shared between two instance of A type [line 2]
  2. What's implications according to following code ?

class A implements Runnable {
    String str = "hello"; // line 2.

    public void run(){
        Synchronized(str){
            System.out.println(str+" "+Thread.currentThread().getName());
            Thread.sleep(100);
            System.out.println(str+" "+Thread.currentThread().getName());
            //anything
        }
    }

    public void static main(String[] args){  
        Thread one = new Thread(new A(),"one").start();  
        Thread two = new Thread(new A(),"two").start();  
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The field itself isn't shared between two instances. They are distinct fields. However, they start off with the same value, as string literals are interned.

That means when the synchronized block acquires the string's monitor in one thread, it will prevent the other thread from acquiring the same monitor. It's important to understand that the synchronized block is acquiring the lock for the monitor associated with the value of the field - it doesn't matter that there are two separate fields involved.

Moral: don't synchronize on strings, particularly literals. Literals are particularly bad, because in this case you could have another class with the same code as A, and that would also try to synchronize using the same monitor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...