components in a new class library
The Java SE5 Java.util.concurrent introduces a number of new classes designed to solve concurrency problems. Learning to use them will help you write simpler and stronger concurrent programs. 1. Countdownlatch
He is used to synchronize one or more tasks, forcing them to wait for a set of operations performed by other tasks to complete.
You can set an initial count value to the Countdownlatch object, and any call to the wait () method on the object will block until the count reaches 0. When other tasks end their work, you Can steal Countdown () on the object to reduce this count value. The Countdownlatch is designed to be triggered only once and the value cannot be reset. If you need to be able to reset the count value of the version, you can use Cyclicbarrier.
The task that calls Countdown () is not blocked when the call is generated, and only calls to await () are blocked until the count reaches 0.
The typical use of Countdownlatch is to have a program atmosphere n a mutually independent solution task and create a Countdownlatch value of 0. When each task completes, the countdown () is invoked on the latch. Wait for the problem. The task of resolving to call await () on this latch, stop them themselves until the latch count is over. Here is a sample framework for demonstrating this technique:
public class Countdownlatchdemo {static final int SIZE = 100;
public static void Main (string[] args) throws Exception {Executorservice exec = Executors.newcachedthreadpool ();
Countdownlatch latch = new Countdownlatch (SIZE);
for (int i = 0; i < i++) {Exec.execute (new Waitingtask (latch));
for (int i = 0; i < SIZE; i++) {Exec.execute (new taskportion (latch));
} System.out.println ("Launched All Tasks");
Exec.shutdown ();
} class Taskportion implements Runnable {private static int counter = 0;
private final int id = counter++;
private static Random Rand = new Random (47);
Private final countdownlatch latch;
Taskportion (Countdownlatch latch) {this.latch = latch;
public void Run () {try {doWork ();
Latch.countdown ();
catch (Interruptedexception e) {//acceptable Way to exit } public void DoWork () throws Interruptedexception {TimeUnit.MILLISECONDS.sleep (Rand.nextint (2000));
System.out.println (this + "completed");
Public String toString () {return String.Format ("%1$-3d", id);
} class Waitingtask implements Runnable {private static int counter = 0;
private final int id = counter++;
Private final countdownlatch latch;
Waitingtask (Countdownlatch latch) {this.latch = latch;
public void Run () {try {latch.await ();
System.out.println ("Latch barrier passed for" + this);
catch (Interruptedexception e) {System.out.println (this + "interrupted");
} public String toString () {return String.Format ("Waitingtask%1$-3d", id); }
}
Taskportion will randomly hibernate for a period of time to simulate the completion of this part of the work, while Waitingtask represents the part of the system that must wait until the initial part of the problem is completed. All tasks use the same single countdownlatch defined in Main (). 2. Cyclicbarrier
Cyclicbarrier applies to situations where you want to create a set of tasks that perform tasks in parallel and then wait until the next step, until all tasks are complete (looks like a join ()). It allows all parallel tasks to be lined up at the fence so that they can move forward in a consistent way. This is much like Countdownlatch, except that Countdownlatch is an event that triggers only once, and cyclicbarrier can be reused multiple times.
public class Horserace {static final int finish_line = 75;
Private list
A "fence action" can be provided to Cyclicbarrier, a runnable that is automatically executed when the count reaches 0 o'clock-this is another difference between cyclicbarrier and Countdownlatch. Here, the fence action was created as an anonymous inner class, and he was presented to the Cyclicbarrier constructor. 3. Delayqueue
This is an unbounded blockingqueue that is used to place an object that implements the delayed interface, where the object can only be fetched from the queue when it expires. This queue is ordered, which is the longest delay due for the team header object. If no delay expires, then no header element is Y, and poll () returns Null (because of this, you cannot place null in this queue). 4. Semaphore
Normal locks at any time only allow Yi ' ge ' ren ' wu a task to access a resource, while the count semaphore allows n tasks to access the resource at the same time. You can also view semaphores as a "license" to distribute the use of resources out of the box, although no license objects are actually used.
As an example, consider the concept of object pooling, which manages a limited number of objects that can be checked out when they are used, and can be checked back in when the user is finished. This functionality can be encapsulated into a generic class:
public class Pool<t> {private int size;
Private list<t> items = new arraylist<t> ();
Private volatile boolean[] checkedout;
Private semaphore available;
Public Pool (class<t> classobject, int size) {this.size = size;
Checkedout = new Boolean[size];
Available = new semaphore (size, true);
for (int i = 0; i < size; i++) {try {Items.Add (classobject.newinstance ());
catch (Exception e) {throw new RuntimeException (e);
}} public T CheckOut () throws Interruptedexception {Available.acquire ();
return GetItem ();
public void CheckIn (T x) {if (Releaseitem (x)) {available.release (); } Private synchronized T GetItem () {for (int i = 0; i < size; i++) {if (!checkedout[i)
) {Checkedout[i] = true; Return items.geT (i);
} return null;
Private Synchronized Boolean Releaseitem (T item) {int index = ITEMS.INDEXOF (item);
if (index = = 1) {return false;
} if (Checkedout[index]) {Checkedout[index] = false;
return true;
return false; }
}
In this simplified form, the constructor uses newinstance () to load the object into the pool. If you need a new object, you can call checkout () and submit it to checkin () after use.
To create an example, we can use FAT, which is a costly object type, because his constructor is time-consuming to run:
public class Fat {
private volatile double D;
private static int counter = 0;
Public Fat () {for
(int i = 1; i < 10000 i++) {
D + = (Math.PI + MATH.E)/(double) I;
}
}
public void operation () {
System.out.println (this);
}
Public String toString () {return
"Fat ID:" + D;
}
}
We manage these objects in the pool to limit the impact of this constructor. We can create a task that will check out the Fat objects, hold them for a while and then check them in to test the pool class:
public class Semaphoredemo {final static int SIZE = 25; public static void Main (string[] args) throws Exception {final pool<fat> Pool = new Pool<> (Fat.class,
SIZE);
Executorservice exec = Executors.newcachedthreadpool ();
for (int i = 0; i < SIZE; i++) {Exec.execute (new checkouttask<fat> (pool));
} System.out.println ("All checkouttasks created");
list<fat> list = new arraylist<> ();
for (int i = 0; i < SIZE; i++) {Fat f = pool.checkout ();
SYSTEM.OUT.PRINTLN (i + ": Main () thread checked out");
F.operation ();
List.add (f);
Future<?> blocked = exec.submit (new Runnable () {public void run () {try {
Pool.checkout ();
catch (Interruptedexception e) {System.out.println ("checkout () interrupted");
}}
});
TimeUnit.SECONDS.sleep (2);
Blocked.cancel (TRUE);
System.out.println ("Checking in Objects" + list);
for (Fat f:list) {Pool.checkin (f);
for (Fat f:list) {Pool.checkin (f);
} exec.shutdown ();
} class Checkouttask<t> implements Runnable {private static int counter = 0;
private final int id = counter++;
Private pool<t> Pool;
Public Checkouttask (pool<t> pool) {this.pool = pool;
public void Run () {try {T item = pool.checkout ();
System.out.println (this + "checked out" + Item);
TimeUnit.SECONDS.sleep (1);
System.out.println (this + "checked in" + Item);
Pool.checkin (item); The catch (Interruptedexception e) {//acceptable Way to terminate}} is public String toString ()
{return "Checkouttask" + ID + "";}
}
in Main (), a pool is created that holds a fat object, and a group of Checkouttask begins to drill the pool. The main () thread then checks out the fat objects in the pool, but does not check them in. Once all objects in the pool are checked out, semaphore will no longer be allowed to perform any checkout operations. The blocked run () method is blocked, and after 2 seconds the Cancel () method is invoked to break free of the future's bondage. Note that the redundant Qian ' ru check-in will be ignored by the pool.