Java concurrent programming Practice Notes

Source: Internet
Author: User

1. Three methods to ensure thread security:

A. Do not access Shared variables across threads
B. Make the shared variables of the final type
C. Synchronize the operations on shared Variables

2. It is easier to design a class to be thread-safe at the beginning than to fix it later.

3. Write a multi-threaded program. First, ensure that it is correct, and then consider performance.

4. stateless or read-only objects are always thread-safe.

5. Do not expose a shared variable to a multi-threaded environment (with no synchronization or non-variant protection)

6. Synchronization protection is required for delayed loading in multi-threaded environments, because delayed loading may cause repeated Object Instantiation.

7. It is often insecure to operate the numeric type variables declared by volatile (volatile can only ensure visibility, but cannot guarantee atomicity ).
For details, refer to the discussion on dirty data in volatile principles and techniques.

8. When a thread requests to obtain its own lock (used for nesting of the same lock), we call this lock reentrant lock.
JAVA Implementation-reentrantlock-is provided in the concurrent release of JDK.

9. Each shared variable should be protected by a unique lock.
Create reentrantlock with the same number of variables so that they are responsible for the thread security of each variable.

10. Although narrowing down the scope of the synchronization block can improve the system performance.
However, to ensure atomicity, atomic operations cannot be divided into multiple synchronized blocks.

11. In the absence of synchronization, the command execution sequence between the compiler and the processor may be totally unexpected.
The reason is that the compiler or processor reordering the commands to optimize the execution efficiency ).

12. When a thread reads a variable without synchronization, it may get an expiration value, but at least it can see
A real value set by the thread at that time, instead of a value created out of thin air. This security guarantee is called out-of-thin-air safety)

This unguaranteed approach is sometimes used when developing concurrent applications to greatly improve system throughput and performance.
However, the numeric operation is still rejected.

13. Volatile variables can only ensure visibility and atomicity.

14. For some time-consuming network operations or I/O, make sure that the lock is not occupied during execution.

15. Publish (publish) object, which means that it can be used by code out of the current range. (passed by reference)
Object escaping refers to releasing an object before it is ready.

Principle: to prevent escape, objects must be fully constructed before they can be published (the best solution is to adopt synchronization)

This keyword references object escaping
Example: In the constructor, enable the thread and pass the object "this" to the thread, causing reference transmission.
At this time, the constructor has not been executed, and the object will escape.

16. When necessary, use the threadlocal variable to ensure that the thread is closed (closed threads are often safe, but may cause performance loss to some extent)
Examples of closed objects are common in actual use, such as Hibernate opensessioninview mechanism and JDBC connection mechanism.

17. A single immutable object is often thread-safe (complex immutable objects must ensure that their internal member variables are also immutable)
Good multi-thread programming habits: declare all the domains as final unless they are variable

18. Ensure that the release of shared variables is secure.
A. initialize the object through the static initialization device (JLS 12.4.2 describes that the JVM will ensure that the static initialization variables are synchronized)
B. Declare the object as volatile or use atomicreference.
C. Ensure that the object is unchangeable.
D. All referenced or variable operations are protected by locks.

19. The design of thread-safe classes should include the basic elements:
A. Determine which variables are variable shared.
B. Determine which variables are unchangeable.
C. Specify a policy for managing the status of concurrent access objects

20. encapsulate the data inside the object and ensure that the access to the data is atomic.
We recommend that you use the volatile JavaBean model or construct the synchronized getter and setter.

21. Thread restriction makes it easier to construct a thread-safe class, because when the class State is restricted and Its thread security is analyzed, the complete program does not have to be checked.

22. Writing concurrent programs requires more comprehensive comments and more complete instructions.

23. When you need to allocate subdivided locks, using the Java monitor mode is better than using the monitor lock of your own object.
The former has better flexibility.

Object target = new object ();
// Use an external object as the monitor, instead of this
Synchronized (target ){
// Todo
}

For Java monitor pattern, in fact, the implementation of reentrantlock makes concurrent programming easier.
More powerful.

24,When designing concurrent programs to ensure scalability and performance compromise, the shared variables are prioritized and delegated to thread-safe classes.
It controls global concurrent access.

25. External locks are required to ensure the atomicity of the normal synchronization container (vector, hashtable) iterator.
The reason is that the iterator generated by the common synchronization container is non-thread-safe.

26. When concurrent programming requires container support, JDK concurrent containers are preferred.

(Concurrenthashmap, concurrent1_queue, copyonwritearraylist ...).

27, concurrenthashmap, copyonwritearraylist
Concurrent container iterators, full range size (), and isempty () all show weak consistency.
They can only indicate the container's current data status. They cannot fully respond to changes and modifications after the container.

28,Use a bounded queue to block all read and write operations when the queue is full or empty.(A good solution for achieving production-consumption)
Blockqueue and arrayblockingqueue are implemented under blockue. The former is a linked list, and variable operations are preferred. The latter is an array, and read operations are preferred.
Priorityblockingqueue is a blocking queue in priority order. It can sort all placed elements (implemented by the comparator interface)

29. When a method can throw interruptedexception, it means that this method is a blocking method. If it is interrupted, the blocking state will be terminated early.
When you call a blocking method, it means that it is also called a blocking method, because you must wait for the blocking method to return.

If the blocking method throws an interrupt exception, what we need to do is to throw it to the upper layer, unless it is already the level to capture the exception.
If the current method cannot throw interruptedexception, you can use the thread. currentthread. Interrupt () method to manually interrupt.

Reprinted please indicate the original link: http://kenwublog.com/java-concurrency-in-practise-note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.