HashMap multithreading is not recommended for use

Source: Internet
Author: User
Package com.jay.test.map;

Import Java.util.HashMap;
Import Java.util.Map;
Import Java.util.concurrent.ConcurrentHashMap;

public class Maptest {public

	static void Main (string[] args) {

		final map<integer, integer> Map = new Hashma P<integer, integer> ();		final Map<integer, integer> Map = new concurrenthashmap<integer,integer> ();
		New Thread (New Runnable () {public
			void run () {
				map.put (1, 1);
			}
		}). Start ();
		New Thread (New Runnable () {public
			void run () {
				map.put (2, 1);
			}
		}). Start ();
		New Thread (New Runnable () {public
			void run () {
				map.put (3, 1);
			}
		}). Start ();
		SYSTEM.OUT.PRINTLN (map);
	}

Today on the Internet to see the next multithreading use HashMap will have problems, because HashMap is not thread-safe, multithreading or use Concurrenhashmap this than Hashtable

"Thread-safe" is more efficient. Problems caused by

1, the probability of loss of data, the above program runs, 40% of the probability of loss of data.

{1=1, 2=1}

2, there is the probability of abnormal information, 10% bar.

Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.hashmap$hashiterator.nextentry (Unknown Source)
At Java.util.hashmap$entryiterator.next (Unknown Source)
At Java.util.hashmap$entryiterator.next (Unknown Source)
At java.util.AbstractMap.toString (Unknown Source)
At Java.lang.String.valueOf (Unknown Source)
At Java.io.PrintStream.println (Unknown Source)
At Com.jay.test.map.MapTest.main (maptest.java:28)

In view of the above problems or use Concurrenthashmap bar.

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.