Java Multithreading Performance optimization

Source: Internet
Author: User

Everyone uses multithreading is nothing more than to improve performance, but if the use of multithreading is inappropriate, not only performance improvement is not obvious, and will make the resource consumption greater. Here's a list of points that might cause multi-threading performance issues:

    • Dead lock

    • Too many serialization

    • Excessive lock competition

    • Toggle Context

    • Memory synchronization

The following separate analysis of the above performance problems

Dead lock

On the deadlock, we learn the operating system when we know its cause and harm, here is not from the principle of the statement, you can read from the following code and diagram of the cause of the deadlock:

[Java] view plaincopy

  1. public class Leftrightdeadlock {

  2. Private Final Object left = new Object ();

  3. Private Final Object right = new Object ();

  4. public void LeftRight () {

  5. Synchronized (left) {

  6. Synchronized (right) {

  7. DoSomething ();

  8. }

  9. }

  10. }

  11. public void Rightleft () {

  12. Synchronized (right) {

  13. Synchronized (left) {

  14. Dosomethingelse ();

  15. }

  16. }

  17. }

  18. }

Ways to prevent and handle deadlocks:

1) Try not to compete for other locks before releasing the lock

Generally can be achieved through the refinement of the synchronization method, only in the real need to protect the shared resources where to take the lock, and release the lock as soon as possible, so as to effectively reduce the synchronization method calls other synchronization methods of the situation

2) Sequential Request lock Resource

If it is not possible to avoid nesting request lock resources, you need to develop a policy to request lock resources, first plan what locks, and then each thread in a sequence to obtain, do not appear in the above example in the different order, so there will be a potential deadlock problem

3) Try a timed lock

Java 5 provides a more flexible locking tool that can be used to explicitly request and release locks. Then you can set a time-out when the lock is requested, and if the lock has not been obtained for more than this time, it will not continue to block but give up the task, the sample code is as follows:

[Java] view plaincopy

  1. public boolean trysendonsharedline (String message,

  2. Long timeout, timeunit unit)

  3. Throws Interruptedexception {

  4. Long Nanostolock = Unit.tonanos (timeout)

  5. -Estimatednanostosend (message);

  6. if (!lock.trylock (Nanostolock, nanoseconds))

  7. return false;

  8. try {

  9. return sendonsharedline (message);

  10. } finally {

  11. Lock.unlock ();

  12. }

  13. }

This can effectively break the deadlock condition.

4) Check for deadlocks

The JVM uses thread dump to identify deadlocks by sending a thread dump signal to the JVM through the commands of the operating system, which can be queried for which thread deadlock.

Too many serialization

Multithreading actually wants to do things in parallel, but these things because some dependencies must be serial work, resulting in a lot of serialization, which is actually very limited to the scalability of the system, even if the CPU plus threading, but the performance is not linear growth. There is a Amdahl theorem to illustrate this problem:

Where F is the serialization scale, N is the number of processors, and it is known that the scalability can be maximized only if the serialization is minimized. The key to reduce the serialization is to reduce the lock competition, when many parallel tasks are linked to the acquisition of locks, is the performance of serialization

Excessive lock competition

The danger of too much lock competition is self-evident, then see what ways to reduce the lock competition

1) Reduce the range of locks

This is also mentioned earlier, as far as possible to narrow the scope of lock protection, fast forward and fast, so try not to use the Synchronized keyword directly on the method, but only in the real need of thread security to use the place

2) Reduce the size of the lock

Java 5 provides an explicit lock, which allows for more flexibility in protecting shared variables. The Synchronized keyword (used in the method) is the default to take the entire object as a lock, in fact, many times it is not necessary to use such a large lock, which causes all synchronized of this class to be executed serially. You can use a shared variable that you really need to protect as a lock, or a more granular strategy that is designed to be serialized when it really needs to be serialized, to give an example:

[Java] view plaincopy

  1. public class Stripedmap {

  2. Synchronization Policy:buckets[n] guarded by locks[n%n_locks]

  3. private static final int n_locks = 16;

  4. Private final node[] buckets;

  5. Private final object[] locks;

  6. private static Class Node {...}

  7. Public stripedmap (int numbuckets) {

  8. Buckets = new Node[numbuckets];

  9. Locks = new Object[n_locks];

  10. for (int i = 0; i < n_locks; i++)

  11. Locks[i] = new Object ();

  12. }

  13. Private final int hash (Object key) {

  14. Return Math.Abs (Key.hashcode ()% buckets.length);

  15. }

  16. public object get (object key) {

  17. int hash = hash (key);

  18. Synchronized (locks[hash% n_locks]) {

  19. for (Node m = Buckets[hash]; m = null; m = m.next)

  20. if (M.key.equals (key))

  21. return m.value;

  22. }

  23. return null;

  24. }

  25. public void Clear () {

  26. for (int i = 0; i < buckets.length; i++) {

  27. Synchronized (locks[i% n_locks]) {

  28. Buckets[i] = null;

  29. }

  30. }

  31. }

  32. ...

  33. }

The above example is a hash algorithm to access the value of the corresponding hash value as a lock, so that only the same hash value of the same object access serialization, and not as Hashtable as any object of any operation is serialized.

3) Reduce the reliance on shared resources

Shared resources are the source of competition lock, in the multi-threaded development to minimize the reliance on shared resources, such as Object pool technology should be considered carefully, the new JVM to create new objects to do enough optimization, performance is very good, if the use of object pool not only can not improve the performance, but because of the lock competition to reduce the concurrency of the thread.

4) Replace exclusive lock with read-write separation lock

Java 5 provides a read-write separation lock (Readwritelock) for reading-and-read concurrency, read-and-writes serial, and write-write serial features. This approach further increases concurrency because some scenarios are mostly read, so there is no need to work serially. For specific use of readwritelock you can take a look at the example:

[Java] view plaincopy

  1. public class Readwritemap<k,v> {

  2. Private final map<k,v> Map;

  3. Private final Readwritelock lock = new Reentrantreadwritelock ();

  4. Private final Lock R = Lock.readlock ();

  5. Private final Lock w = Lock.writelock ();

  6. Public Readwritemap (map<k,v> Map) {

  7. This.map = map;

  8. }

  9. Public V put (K key, V value) {

  10. W.lock ();

  11. try {

  12. Return Map.put (key, value);

  13. } finally {

  14. W.unlock ();

  15. }

  16. }

  17. Do the same for remove (), Putall (), Clear ()

  18. Public V get (Object key) {

  19. R.lock ();

  20. try {

  21. return Map.get (key);

  22. } finally {

  23. R.unlock ();

  24. }

  25. }

  26. Do the same for other read-only Map methods

  27. }

Toggle Context

When the thread is more, the operating system switching thread context performance consumption is not negligible, in building high-performance Web------Web server long connection can see the cost of process switching, of course, threads will be lighter, but the reason is similar

Memory synchronization

When used to synchronized, volatile, or lock, it is not possible to enjoy the performance optimizations of the JMM structure in order to ensure that the visibility results in more memory synchronization.

Java Multithreading Performance optimization

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.