`
leonzhx
  • 浏览: 767999 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 66: Synchronize access to shared mutable data

阅读更多

1.  Without synchronization, one thread’s changes might not be visible to other threads. Not only does synchronization prevent a thread from observing an object in an inconsistent state, but it ensures that each thread entering a synchronized method or block sees the effects of all previous modifications that were guarded by the same lock.

 

2.  Reading a variable other than a long or double is guaranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently and without synchronization. (atomic)

 

3.  The advice that to improve performance, you should avoid synchronization when reading or writing atomic data is dangerously wrong. Synchronization is required for reliable communication between threads as well as for mutual exclusion.

 

4.  The Thread.stop method, but this method was deprecated long ago because it is inherently unsafe—its use can result in data corruption. Do not use Thread.stop.

 

5.  In the absence of synchronization, it’s quite acceptable for the virtual machine to transform this code:

while (!done)
  i++;

 

into this code:

if (!done)
  while (true)
    i++;

 

This optimization is known as hoisting, and it is precisely what the HotSpot server VM does. 

 

6.  Synchronization has no effect unless both read and write operations are synchronized.

 

7.  While the volatile modifier performs no mutual exclusion, it guarantees that any thread that reads the field will see the most recently written value.

 

8.  Either share immutable data, or don’t share at all. In other words, confine mutable data to a single thread.

 

9.  It is acceptable for one thread to modify a data object for a while and then to share it with other threads, synchronizing only the act of sharing the object reference. Other threads can then read the object without further synchronization, so long as it isn’t modified again. Such objects are said to be effectively immutable. Transferring such an object reference from one thread to others is called safe publication. There are many ways to safely publish an object reference: you can store it in a static field as part of class initialization; you can store it in a volatile field, a final field, or a field that is accessed with normal locking; or you can put it into a concurrent collection.

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics