Chapter 2. Thread Safety

来源:互联网 发布:淘宝同城的怎么搜索 编辑:程序博客网 时间:2024/05/17 01:19
Chapter 2. Thread Safety
     informally, an object's state is its data, stored in state variables such as instance or static fields.
     
Copy
If multiple threads access the same mutable state variable without appropriate synchronization, your program isbroken. There are three ways to fix it:x Don't share the state variable across threads;x Make the state variable immutable; orx Use synchronization whenever accessing the state variable.

     

  

Copy
When designing thread?safe classes, good object-oriented techniques  encapsulation, immutability, and clear
specification of invariants are your best friends.

    

  

Copy
A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or
interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or
other coordination on the part of the calling code.

  

Intrinsic Locks 
A synchronized block has two parts: a reference to an object that will serve as the lock, and a block of code to be
guarded by that lock. A synchronized method is shorthand for a synchronized block that spans an entire methodbody, and whose lock is the object on which the method is being invoked. (Static synchronized methods use the Classobject for the lock.)
Reentrancy 
     When a thread requests a lock that is already held by another thread, the requesting thread blocks. But becauseintrinsic locks are reentrant, if a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancymeans that locks are acquired on a per-thread rather than per-invocation basis. [7] Reentrancy is implemented byassociating with each lock an acquisition count and an owning thread. When the count is zero, the lock is consideredunheld. When a thread acquires a previously unheld lock, the JVM records the owner and sets the acquisition count toone. If that same thread acquires the lock again, the count is incremented, and when the owning thread exits thesynchronized block, the count is decremented. When the count reaches zero, the lock is released



0 0
原创粉丝点击