Java Multithreading considerations

Source: Internet
Author: User
Tags dateformat volatile

Turn from: 56279659java Multithreading considerationsFebruary 21, 2017 12:42:42Hits: 1753One, the role of the thread pool's conceptual thread pool: the role of the thread pool is to limit the number of threads executing in the system.
According to the environment of the system, the number of threads can be set automatically or manually to achieve the best performance; less waste of system resources, more caused by the system congestion efficiency is not high. Use the thread pool to control the number of threads and other threads to wait. A task is completed, and then the first task from the queue is executed. If there is no waiting process in the queue, this resource of the thread pool is waiting. When a new task needs to run, it can start running if there are waiting worker threads in the thread pool, otherwise enter the wait queue.
Why use a thread pool: 1. Reduces the number of times a thread is created and destroyed, and each worker thread can be reused to perform multiple tasks.
2. You can adjust the number of threads in the thread pool according to the endurance of the system, prevent the server from being exhausted because it consumes too much memory (approximately 1MB of memory per thread, the more threads open, the more memory is consumed and the last crashes).
The top interface of the thread pool in Java is executor, but strictly speaking, executor is not a thread pool, but a tool for executing threads. The real thread pool interface is executorservice.


Second, thread resources must be provided through the wire pool and do not allow self-explicitly created thread descriptions in the app: the benefit of using the thread pool is to reduce the time spent on creating and destroying threads and the overhead of system resources to solve the problem of insufficient resources.
If you do not use a thread pool, it can cause the system to create a large number of similar threads that consume memory or "over-switch" issues.


Third, SimpleDateFormat is a thread unsafe class, generally not defined as a static variable, if defined as static, must be locked, or use the Dateutils tool class. Positive example: note thread safety, using Dateutils. The following treatments are also recommended:
private static final threadlocal<dateformat> df = new Threadlocal<dateformat> () {
@Override
protected DateFormat InitialValue () {
return new SimpleDateFormat ("Yyyy-mm-dd");
}
};
Note: If the application is JDK8, you can use instant instead of date,localdatetime instead of Calendar,datetimeformatter instead of Simpledateformatter,
The official explanation: simple beautiful strong immutable thread-safe.


Four, high concurrency, synchronous calls should consider the performance of the lock loss. can use the lock-free data structure, do not use locks, can lock blocks, do not lock the entire method body, you can use the object lock, do not use class lock.


Five, when you lock multiple resources, database tables, objects at the same time, you need to maintain a consistent lock order, otherwise it may cause deadlock. Note: The thread needs to be locked in the form a, B, C in order to be able to update the operation,
Then the lock order of the line Cheng must also be a, B, C, otherwise there may be deadlock.


Six, when concurrently modifying the same record, to avoid the loss of updates, either in the application layer lock, either in the cache lock, or at the database layer using optimistic lock, use version as the update basis. Note: If the probability of each access violation is less than 20%, optimistic locking is recommended, otherwise pessimistic locks are used. The number of retries for optimistic locks must not be less than 3 times.


Seven, multi-threaded parallel processing of timed tasks, when the timer runs multiple timetask, as long as one of them does not catch the thrown exception, the other tasks will automatically terminate the operation, using Scheduledexecutorservice does not have this problem.


Eight, use Countdownlatch for asynchronous to synchronous operation, each thread exits must call countdown method before exiting, thread executes code notice catch exception, ensure Countdown method can execute,
Avoid the main thread being unable to execute to the countdown method until the timeout returns the result. Description: Note that the child thread throws an exception stack and cannot be try-catch to the main thread.


Nine, avoid the use of random instances by multithreading, although sharing the instance is thread-safe, but will cause performance degradation due to competing for the same seed. Description: The Random instance includes an instance of Java.util.Random or a math.random () instance.
A positive example: After JDK7, you can use the API Threadlocalrandom directly, before JDK7, you can do one instance per thread.


Ten, the problem of optimization of delay initialization is realized by double check lock (double-checked locking) (in concurrency scenario) (refer to the "double-checked locking is Broken" Declaration), The recommended problem solution is a simpler one (for JDK5 and above), which declares the target attribute as volatile.
Counter Example:
Class Foo {
Private helper helper = null;
Public Helper Gethelper () {
if (helper = = null) synchronized (this) {
if (helper = = null)
Helper = new Helper ();
}
return helper;
}
Other functions and members ...
}


11, volatile resolves the problem of multi-threaded memory invisibility. For a write multi-read, it is possible to solve the variable synchronization problem, but if you write more, the same cannot solve the thread safety problem.
If this is a count++ operation, use the following class implementation: Atomicinteger count = new Atomicinteger (); Count.addandget (1);
In the case of JDK8, it is recommended to use the Longadder object, which is better than atomiclong (reducing the number of retries for optimistic locking).




12, HashMap when the capacity is not enough to resize due to high concurrency can be a dead chain, causing the CPU to soar, in the development process to avoid this risk.

13, Threadlocal cannot resolve update issues for shared objects, threadlocal objects recommend using the static modifier. This variable is common to all operations within a thread, so it is set to a static variable,
All such instances share this static variable, that is, when the class is used for the first time, only one storage space is allocated, and all objects of this class (as defined within this thread) can manipulate the variable.

Java Multithreading considerations

Related Article

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.