Locking on Strings

前端 未结 2 1109
挽巷
挽巷 2021-01-17 02:00

2 Questions:

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



        
2条回答
  •  梦毁少年i
    2021-01-17 02:17

    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.

提交回复
热议问题