Several methods of implementing synchronization in Map threads

Source: Internet
Author: User

If you need to make the MAP thread safe, there are roughly four ways to do it:
1, the use of synchronized keyword, the code is as follows Java code 1. Synchronized (AnObject) {2. Value = Map.get (key); 3.} 2, use the lock provided by JDK1.5 (Java.util.concurrent.locks.Lock). The code is as follows
Java code 1. Lock.lock (); 2. Value = Map.get (key); 3. Lock.unlock (); 3, use JDK1.5 to provide read-write lock (Java.util.concurrent.locks.ReadWriteLock). The code is as follows
Java code 1. Rwlock.readlock (). Lock (); 2. Value = Map.get (key); 3. Rwlock.readlock (). Unlock (); Such two read operations can be done at the same time, theoretically more efficient than the method 2.

4. Use the Java.util.concurrent.ConcurrentHashMap class provided by JDK1.5. This class divides the storage space of the MAP into blocks, each with its own lock, which greatly reduces the number of threads competing for the same lock. The code is as follows
Value = Map.get (key); The synchronization mechanism is built into the Get method

Comparison:

1, the different steps are indeed the fastest, consistent with the expected.
2, four kinds of synchronous mode, Concurrenthashmap is the fastest, close to the situation of the synchronization.
3, the Synchronized keyword is very slow, compared with the use of locks two orders of magnitude. If you need to implement synchronization yourself, use the lock mechanism provided by JDK1.5 to avoid using the Synchronized keyword.

Java code 1. public class maptest{2. public static final int thread_count = 1; 3. public static final int map_size = 1000; 4. public static final int execution_milles = 1000; 5. public static final int[] KEYS = new int[100]; 6. public static void Main (string[] args) throws exception{7. 8.//Initialization of 9. Random rand = new Random (); for (int i = 0; i < keys.length ++i) keys[i] = Rand.nextint (); 11.//Create thread 12. Long start = System.currenttimemillis (); thread[] threads = new Thread[thread_count]; for (int i = 0; i < Thread_count ++i) {threads[i] = new Synchronizedthread (); //threads[i] = new Lockthread (); Threads[i].start (); 18.} 19. 20.//Waiting for other threads to execute for some time 21. Thread.Sleep (Execution_milles); 22.//Statistics The number of get operations 23. Long sum = 0; for (int i = 0; i < Thread_count ++i) {+ + + = Threads[i].getclass (). Getdeclaredfield ("COUNT"). Getlong (threads[ I]); } 26. Long milliscost = System.currenttimemillis ()-Start; SYSTEM.OUT.PRINTLN (sum + "(" + (Milliscost) + "MS"); System.exit (0); 29.} 30. public static void Fillmap (Map<integer, integer> Map) {32. Random rand = new Random (); for (int i = 0; i < map_size ++i) {map.put (Rand.nextint (), Rand.nextint ()); 35.} 36. } 37. } 38. Class Synchronizedthread extends thread{the private static Map<integer, integer> Map = new Hashmap<integer, inte Ger> (); -Public Long Count = 0; static {42. Maptest.fillmap (map); 43.} 44. public void Run () {A. for (;;) {+. int index = (int) (count% MapTest.KEYS.length); Synchronized (Synchronizedthread.class) {map.get (Maptest.keys[index]); 49.} 50. ++count; 51.} 52. } 53. } 54. 55.56. Class Lockthread extends thread{. private static Map<integer, integer> Map = new Hashmap<integer, integer& gt; (); private static lock lock = new Reentrantlock (); -Public Long Count = 0; static {62. Maptest.fillmap (map); 63.} 64. public void Run () {A for (;;) {total. int index = (int) (count% MapTest.KEYS.lenGTH); Lock.lock (); Map.get (Maptest.keys[index]); Lock.unlock (); ++count; 71.} 72. } 73. The difference between the following two ways:
Synchronized (anobject) {value = Map.get (key);     } synchronized (AnObject) {map.put (key, value); }

Synchronized (AnObject)  
{  
    value = Map.get (key);  
}
Synchronized (AnObject)  
{  
    map.put (key, value);  
}

This is thread-safe, as long as it's guaranteed that put and get are synchronized to this anobject.

Synchronized (key) {value = Map.get (key);    } synchronized (key) {Map.put (key, value); }
Synchronized (key)  
{  
    value = Map.get (key);  
} 
Synchronized (key)  
{  
    map.put (key, value); 
}

This type of writing may be problematic because get and put key may be different objects

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.