Java concurrency-Synchronizing container classes

Source: Internet
Author: User

The Java Platform Class library contains a rich set of concurrent infrastructure modules, such as thread-safe container classes and a variety of synchronization tool classes used to coordinate multiple mutually collaborative thread control flows.

Synchronizing Container classes

The synchronization container classes, including vectors and Hashtable, are part of the early JDK and are also created by factory methods such as Collections.synchronizedxxx. These classes are implemented in a secure manner by encapsulating their state and synchronizing each public method so that only one thread can access the state of the container at a time.

The synchronization container classes are thread-safe, but for some composite operations, additional locking are required to protect them. Common compound operations are: iterations (repeatedly accessing elements until all elements are traversed), jumps (finds the next element of the current period element in the specified order), and conditional operations (e.g., if not added).

 Public Static Object getlast (Vector list) {    int lastIndex = list.size ()-1;     return list.get (LastIndex)}  Public Static void deletelast (Vector list) {    int lastIndex = list.size ()-1;    List.remove (LastIndex);}

In the example above, there are two methods defined in the vector, all of which perform a check and run operation first. Gets the array size first, and then gets or deletes the last element. These methods look fine and are thread-safe and do not destroy vectors. But from the caller's point of view, there is a problem. While a thread may call GetLast, the B thread calls the Deletelast,vector element less, causing a thread call to fail.

The

Synchronization container class adheres to the synchronization policy, which is to support client-side locking, so that we can create new operations as long as we know that the lock should be used. These new operations are atomic operations with containers and other operations. The synchronization container uses its own locks to protect each of its methods . By acquiring a lock on the container, you can make the above method known as an atomic operation. There is no other action between the size and get operations.

 Public Static Object getlast (Vector list) {    synchronized(list) {        int lastIndex = List.size ()-1;         return list.get (lastIndex)    }    }  Public Static void deletelast (Vector list) {    synchronized(list) {        int lastIndex = List.size ()-1;        List.remove (LastIndex);    }}

The same problem will occur on the traversal, as in the following example:

 for (int i=0; i< vector.size (); i++)    dosomgthing (Vector.get (i));

If another thread deletes an element, it causes a arrayindexoutboundsexception exception. We can solve the iterative unreliable problem by locking and avoid other threads modifying the vector during the traversal process. However, it also brings performance issues that cannot be accessed by other threads during the iteration.

synchronized (vector) {    for (int i=0; i< vector.size (); i++)        dosomgthing (Vector.get (i) );}

The above example can throw an exception without locking, which does not mean that the vector is not thread-safe. Vectors are still thread-safe, and the exceptions thrown are consistent with their specifications.

Iterators and Concurrentmodificationexception

The standard way to iterate over a container is to use iterator, using the For-each syntax, and also calling iterator. The concurrency modification problem is not considered when designing a synchronization container class, and they exhibit the behavior of "failure in time", which means that if there are other threads modifying the container during the iteration, the Concurrentmodificationexception exception is thrown. They are implemented by associating the counter changes with the container, and the iterative device counter being modified, then hasnext or next throws an exception. This is a tradeoff in design.

To avoid concurrentmodificationexception, you must hold the lock of the container during the iteration. However, if the container size is large, the iterative process holds the lock, which can cause serious performance problems. One alternative is to "clone the container" and iterate over the copy. The cloning process still needs to be locked, while there is a significant performance overhead. Cloning a container is good or bad depending on the elements, such as the size of the container, the actions that each element performs, and so on.

Hide Iterators

  Locking prevents an iteration from throwing a concurrentmodificationexception exception, but it needs to be locked in place at all iterations. The actual situation is often more complex, and in some cases the hidden iterator may be ignored.

  

 Public classhiddeniterator{Private FinalSet (Integer) set =NewHashset<>();  Public synchronized voidAdd (Integer i) {Set.add (i)} Public synchronized voidRemove (Integer i) {set.remove (i)} Public voidaddtenthings () {Random R=NewRandom ();  for(inti=0;i<10;i++) {Add (R.nextint ()); } System.out.println ("Debug" +set)}}

The Addtenthings method might throw a Concurrentmodificationexception exception because a string connection is made when the output is printed, and the ToString method of the set is called, and the ToString method iterates over the container. You must obtain the Hiddeniterator lock before using println, but the actual application may be ignored.

Encapsulating the state of an object helps maintain immutability, and the synchronization mechanism of encapsulated objects helps ensure that synchronization policies are implemented.

This error does not occur if you use Synchronizedset to wrap the hashset, and the synchronization code is encapsulated.

In addition to methods such as Tostring,hashcode and equals, iterative operations are also performed indirectly. This occurs when the container is an element and a key value for another container. Similarly, methods such as Containsall,removeall, as well as constructors that use containers as parameters, iterate over the container. These indirect operations are likely to throw concurrentmodificationexception exceptions.

Java concurrency-Synchronizing container classes

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.