Do you still use notify() and wait() explicitly?

As some other people will say Threads can be your best friend or worse enemy...that is, if you're still entangled with your synchronization and you're still hand coding your notify() and wait() statements and still wondering where to put them. OR do you still create your own Thread objects and execute them yourself?

Thanks to Doug Lea's Concurrent API, synchronization becomes a breeze. One of the most useful is the LinkedQueue class which is an implementation of the Channel Interface. To get a glimpse of what it does, first let's build a sample code. This snippet will simply try to perform a JMS-style send-and-listen message pass. First the take() method will be initiated and "waits" for the message to "come in" via the put() method.



import EDU.oswego.cs.dl.util.concurrent.Channel;
import EDU.oswego.cs.dl.util.concurrent.LinkedQueue;

/**
* Description:
*
* @author Jared Odulio
*
*
*/
public class ConcurrentTest {

private Channel channel;
private String message = "Bobsled";

/**
*
*/
public ConcurrentTest() {
super();
channel = new LinkedQueue();

}

public void takeME(){

try {
String taker = (String)channel.take();
System.out.println(taker + " just slided in...");
} catch (InterruptedException e) {

e.printStackTrace();
}
}

public void putME(){

try {
channel.put(message);
} catch (InterruptedException e) {

e.printStackTrace();
}
}

public void initialize(){

Taker take = new Taker();
take.start();
System.out.println("Taker started");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Putter put = new Putter();
put.start();

}

public static void main(String[] args){

new ConcurrentTest().initialize();

}

class Putter extends Thread{
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
// TODO Auto-generated method stub
putME();
}

}

class Taker extends Thread{
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
// TODO Auto-generated method stub
takeME();
}
}
}





And the output would be:



Taker started



And after 3 seconds:



Bobsled just slided in...

Comments

Popular Posts