- Building Thread-Safe classes
- Volatile
Only data visibility is guaranteed and data synchronization is not guaranteed. That is, the JVM only guarantees that the most recent values are exposed to all threads after using volatile data changes, and that there is no multiple limit on the operation of the cached data within the thread. Multiple threads changing a shared volatile data at the same time does not produce the correct results.
- You can use volatile when the following conditions are true:
1. Write a variable without relying on the current value of the variable, or you can ensure that only a single thread modifies the value of the variable.
2. Variables do not need to participate in invariant constraints with other variables.
3. There is no other reason to lock when accessing a variable.
- Long and double
- Release
- Escape
- Secure Release Mode
Initializes an object reference through a static initializer;
Storing its references to volatile or atomicreference;
Store its references in a properly created final domain, or in a lock-protected domain.
- Secure shared objects
Thread limit: A thread-restricted object that is exclusive to the thread and can only be modified by the thread that owns it (such as threadlocal type data).
Shared read-only: A shared read-only object.
Shared thread safety: A thread-safe object is internally synchronized so that other threads can be accessed without additional synchronization.
Guarded (Guarded): A published object that is protected by a lock.
- Thread-Safe Composite objects
- Avoid risk of activity
- Dead lock
- Lock sequence Deadlock (lock-ordering deadlock)
Lock order deadlocks Do not occur if all threads acquire locks in a common, fixed order.
The method (A, A, b) parameter represents an instance that may be the same instance but in a different order. such as transfer, from me-he and from him-I, the lock order is different.
- Resource Deadlock (Resource deadlock)
- Deadlock between collaboration objects
- Open Call
- Avoiding and diagnosing deadlocks
- Try a timed lock
- Parsing deadlocks by thread dump
- Other active risk (loss of signal, live Lock)
- Hunger (starvation)
- Weak responsiveness
- Live Lock (Livelock)
- Performance and Scalability
This article is from the Java Technology Stack notes blog, so be sure to keep this source http://stroll.blog.51cto.com/11038467/1854528
Multithreading (ii) Building thread-safe classes