Five things you don't know--java.util.concurrent (Part One)

Source: Internet
Author: User


                                                           

This is one of the 5 things series articles from the IBM Developerworks in the Ted Neward, which describes some of the application tips for the Java Concurrency Collection API that you should learn. (Last updated 2010.05.24)

Summary: It is really hard to write multithreaded code that is both good performance and prevents application crashes-that's why we need to java.util.concurrent. Ted Neward shows you how concurrent collection classes like Copyonwritearraylist,blockingqueue and Concurrentmap improve the standard collection classes for concurrent programming needs.

The Concurrency Collection API is a great feature of Java 5, but many Java developers overlook these APIs because of the annotation and generics. In addition (possibly more true), because many developers suspect that the Concurrency collection API must be complex, like trying to solve some problems, developers will avoid java.util.concurrent packages.
In fact, many of Java.util.concurrent's classes do not require you to be very aggressive in solving common concurrency problems efficiently. Keep looking, and you'll learn how classes like Copyonwritearraylist and Blockingqueue in Java.util.concurrent can help you solve the daunting challenges of multithreaded programming.

1. Timeunit
Java.util.concurrent.TimeUnit itself is not a collection framework class, this enumeration makes the code very easy to read. Using Timeunit can free developers from the difficulties associated with milliseconds and switch to their own methods or APIs.
Timeunit can work with all time units, ranging from milliseconds and microseconds to days and hours, which means it can handle almost any type of time that a developer might use. Also thanks to this enumeration type declaration of the time conversion method, when the time is faster, it can even fine to the hour to convert back to milliseconds.

2. Copyonwritearraylist
Making a clean copy of an array is a costly operation that has overhead in both time and memory, so that the method cannot be considered in the usual application, and developers often resort to using synchronous ArrayList instead of the aforementioned method. But this is also a costly option, because every time you iterate through the contents of the collection, you have to synchronize all the methods, including read and write, to ensure memory consistency.
This approach will slow down the cost structure in a scenario where a large number of users are reading ArrayList and only a few users have modified it.
Copyonwritearraylist is an excellent tool for the baby to solve this problem. Its Javadoc describes the ArrayList by creating a clean copy of the array for mutable operations (additions, modifications, and so on), while Copyonwritearraylist is a "thread-safe" variant of ArrayList.
For any modification operation, the collection class will internally copy its contents into a new array, so the read user accesses the contents of the array without incurring any synchronization overhead (because they do not operate on mutable data).
In essence, the idea of creating copyonwritearraylist is to deal with scenarios where ArrayList cannot meet our requirements: frequently read, and rarely write, collection objects, such as listener for JavaBean events.

3. Blockingqueue
The Blockingqueue interface indicates that it is a queue, which means that its elements are stored in FIFO order. Elements inserted in a particular order are taken out in the same order--but depending on the insert guarantee, any attempt to remove elements from an empty queue blocks the calling thread until the element can be removed. Similarly, any attempt to insert an element into a full queue will block the calling thread until the queue's storage space is free.
When you don't need to explicitly focus on synchronization issues, how to "hand over" the elements that are clustered by one thread to another thread, Blockingqueue solves the problem very cleverly. The guarded blocks section of Java Tutorial is a good example. It uses the manual synchronization and the Wait ()/notifyall () method to create a single point (single-slot) Limited buffer, which signals between threads when a new element can be consumed and when the point is ready to be populated by a new element. (See guarded Blocks for details)
Although the code in tutorial guarded blocks works correctly, it is long, messy, and completely non-intuitive. Admittedly, in the early days of the Java platform, Java developers had to, but it's been 2010 years now--has the problem been improved?
The program shown in Listing 1 overrides the code in guarded blocks, where I used arrayblockingqueue instead of a hand-written drop.

Listing 1. Blockingqueue

ImportJava.util.*;Importjava.util.concurrent.*;classProducerImplementsrunnable{PrivateBlockingqueue<string>drop; List<String> messages =Arrays.aslist ("Mares Eat oats",        "Does Eat oats",        "Little Lambs eat Ivy",        "Wouldn ' t you eat ivy too?");  PublicProducer (blockingqueue<string> D) { This. Drop =D;}  Public voidrun () {Try        {             for(String s:messages) drop.put (s); Drop.put ("Done"); }        Catch(interruptedexception intEx) {System.out.println ("interrupted!" + "last one out, turn out the lights!"); }    }    }classConsumerImplementsrunnable{PrivateBlockingqueue<string>drop;  PublicConsumer (blockingqueue<string> D) { This. Drop =D;}  Public voidrun () {Try{String msg=NULL;  while(! (msg = Drop.take ()). Equals ("Done"))) System.out.println (msg); }        Catch(interruptedexception intEx) {System.out.println ("interrupted!" + "last one out, turn out the lights!"); }    }} Public classabqapp{ Public Static voidMain (string[] args) {Blockingqueue<String> drop =NewArrayblockingqueue (1,true); (NewThread (NewProducer (drop)).        Start (); (NewThread (NewConsumer (drop)).    Start (); }}

Arrayblockingqueue also advocates "fairness"-meaning that it can give read and write lines Cheng first-out access order. This approach may be a more efficient strategy, but it also increases the risk of thread starvation. (That is, when other read threads hold a lock, the policy is more efficient at allowing the read thread to execute, but this also creates the risk that a constant stream of read threads will always make the write thread impossible to execute)
Blockingqueue also supports the use of time parameters in methods where the method needs to be returned to emit a signal that the operation failed when inserting or removing an element, which specifies how long the time parameter should be blocked before returning.

4. Concurrentmap
Map has some minor concurrency bugs that can lead many careless Java developers astray. Concurrentmap is a simple decision-making scheme.
When multiple threads are accessing a map, usually the method ContainsKey () or get () is used to determine whether the given key exists before a key/value pair is stored. Even with a synchronized map, a thread can still sneak into the process and gain control over the map. The problem is that the lock is obtained at the beginning of the Get () method, and then it is released before the method put () is called to regain the lock. This leads to a race condition: the competition between two threads, depending on which thread executes first, the results will vary.
If two threads call a method at the same time, if a test key exists, and the other is placed into a new key/value pair, the value of the first thread will be lost during this process. Fortunately, the Concurrentmap interface supports an additional set of methods designed to do two things in one lock: for example, Putifabsent () is tested first, and then the placement operation is performed only if the key is not stored in the map.

5. Synchronousqueues
According to Javadoc's description, Synchronousqueue is a very interesting creation:
A blocking queue must wait for another thread to execute the corresponding delete threads in each insert operation, and vice versa. The synchronization queue does not have any internal storage space and none.
Essentially, Synchronousqueue is another implementation of the previously mentioned Blockingqueue. Using the blocking semantics used by Arrayblockingqueue, Synchronousqueue gives us a very lightweight way to exchange individual elements between two threads. In Listing 2, I rewrote the code in Listing 1 with Synchronousqueue instead of Arrayblockingqueue:

Listing 2 Synchronousqueue

ImportJava.util.*;Importjava.util.concurrent.*;classProducerImplementsrunnable{PrivateBlockingqueue<string>drop; List<String> messages =Arrays.aslist ("Mares Eat oats",        "Does Eat oats",        "Little Lambs eat Ivy",        "Wouldn ' t you eat ivy too?");  PublicProducer (blockingqueue<string> D) { This. Drop =D;}  Public voidrun () {Try        {             for(String s:messages) drop.put (s); Drop.put ("Done"); }        Catch(interruptedexception intEx) {System.out.println ("interrupted!" + "last one out, turn out the lights!"); }    }    }classConsumerImplementsrunnable{PrivateBlockingqueue<string>drop;  PublicConsumer (blockingqueue<string> D) { This. Drop =D;}  Public voidrun () {Try{String msg=NULL;  while(! (msg = Drop.take ()). Equals ("Done"))) System.out.println (msg); }        Catch(interruptedexception intEx) {System.out.println ("interrupted!" + "last one out, turn out the lights!"); }    }} Public classsynqapp{ Public Static voidMain (string[] args) {Blockingqueue<String> drop =NewSynchronousqueue<string>(); (NewThread (NewProducer (drop)).        Start (); (NewThread (NewConsumer (drop)).    Start (); }}

The implementation looks almost the same, but the application has added a new benefit, in which synchronousqueue allows the element to be inserted into the queue only if the thread is waiting to consume an element.
In practice, Synchronousqueue is similar to "Rendezvous Channel (Rendezvous Channel)" in languages such as Ada or CSP. In other environments, it is sometimes referred to as a "connection."

Conclusion
Why bother to introduce concurrency into the collection framework when the Java Runtime Class Library has already provided the handy equivalents in advance? The next article in this series explores more about the Java.util.concurrent namespace.

Five things you don't know--java.util.concurrent (Part One)

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.