Problem exceptions in map usage java.util.ConcurrentModificationException

Source: Internet
Author: User
Tags concurrentmodificationexception

I want to do a buffer on data access, choose Map to do buffer containers, considering the efficiency I chose the HashMap

Think about looping to the inside still or updating the data, so when the system does not access this content, I should be in real time to clear the memory content

As needed, I wrote a static map to do the memory container, and then set up a spring timer to periodically check and process those data needs to clear

However, when the timer processing encountered abnormal java.util.ConcurrentModificationException, encountered thread security problems

Check out the HashMap API introduction:

Note that this implementation is not synchronized. if more than one thread accesses a hash map at the same time, and at least one of the threads modifies the mapping from the structure, it must maintain an external synchronization. (Structural modification means any action that adds or deletes one or more mapping relationships; changing only the value associated with the key that the instance already contains is not a structural modification.) This is typically done by synchronizing the objects that naturally encapsulate the mapping. If no such object exists, you should use the Collections.synchronizedmap method to "wrap" the mapping. It is best to do this at creation time to prevent unexpected, asynchronous access to the mappings, as follows:

   Map m = collections.synchronizedmap (new HashMap (...));

The iterator returned by all of the collection view methods of this class is fast failing: After the iterator is created, if the mapping is modified structurally, except through the Remove method of the iterator itself, any other time in any way, Iterators will throw concurrentmodificationexception. Therefore, in the face of concurrent modifications, the iterator will soon fail completely, without risking any uncertain behavior at a future time of uncertainty.

Note that the rapid failure behavior of the iterator is not guaranteed, and in general, there is no firm guarantee when there are asynchronous concurrent modifications. The fast fail iterator tries its best to throw concurrentmodificationexception. Therefore, it is wrong to write a program that relies on this exception, and the correct approach is that the rapid failure behavior of the iterator should be used only for detecting program errors.

How to solve it.

The API was found, and after 1.5 there was a map object Concurrenthashmap

The introduction is as follows:

A hash table that supports the full concurrency and update of the desired adjustable concurrency of the acquisition. This class adheres to the same functional specification as Hashtable and includes a method version of each method corresponding to Hashtable. However, although all operations are thread safe, the fetch operation does not have to be locked and does not support locking the entire table in a way that prevents all access. This class can interoperate entirely with Hashtable, depending on its thread safety, regardless of its synchronization details.

Getting operations, including get, is usually not blocked, and therefore may overlap with the update operation (including put and remove). Gets the results that affect the most recently completed update operation. For some aggregate operations, such as Putall and clear, concurrent fetching may only affect the insertion and removal of some entries. Similarly, iterators and enumerations return elements that affect the state of a hash table at a point in time when the iterator/enumeration is created or since. They do not throw concurrentmodificationexception. However, the iterator is designed to be used by only one thread at a time.

This allows for the concurrency of the update operation to be booted through an optional Concurrencylevel constructor parameter (the default value of 16), which is used as a hint of internal sizing. Tables are partitioned internally, attempting to allow the number of concurrent updates that are not competing. Because the position in the hash table is basically random, the actual concurrency will be different. Ideally, you should choose a value that accommodates as many threads as possible to modify the table concurrently. Using a value that is much higher than the value you need may waste space and time, while using a value that is clearly lower can cause thread contention. An overestimation or underestimation of the order of magnitude usually has a very significant impact. A value is considered appropriate when only one thread performs a modification operation, and all other threads are simply performing a read operation. In addition, resizing this or any other kind of hash table is a relatively slow operation, so it is a good idea to provide an estimate of the expected table size in the construction method when possible.

This class and its views and iterators implement all of the optional methods of the MAP and iterator interfaces.

This class is similar to Hashtable, but unlike HashMap, it does not allow NULL to be used as a key or value.

The load factor for both objects is 0.75, so you can consider replacing them.

Cache classes: Java code   /**   * @ Description   Memory cache of network values obtained by monitoring    *  @author  cuisuqiang    *  @version  1.0   *  @since    */   public class  jiankongmapkeep {         /**       *   Using thread-safe map objects        */       public static  map<string,jiankongkeep> keepmaps = new concurrenthashmap<string, Jiankongkeep> ();        /**       *  Get a value        *  @param  key       * @ return       */       public static  Jiankongkeep getkeeplistbykey (string key) {            jiankongkeeP jiankongkeep = new jiankongkeep ();            jiankongkeep = keepmaps.get (key);            return jiankongkeep;       }       /**       *  Add or update        *  @param  key       *  @param  jianKongKeep       */        public static void saveorupdatejiankongkeep (String key, Jiankongkeep jiankongkeep) {           keepmaps.put (Key,  jiankongkeep);       }  }  

Timer Execution class: Java code/** * Describes the memory content of the timed cleanup monitoring * @author Cuisuqiang * @version 1.0 * @since/public class Jiankongma Pkeeptimer {public void Checkjiankongkeep () {try {

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: 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.