Showing posts with label Thread. Show all posts
Showing posts with label Thread. Show all posts

Tuesday, November 9, 2010

Executor Completion Service

Scenario: you want to load the tasks in parallel and then wait for the completion of all the tasks.


//Callable is different from Runnable that it returns result
private final class StringTask extends Callable<String>{
public String call(){
//Long operations
return "Run";
}
}

ExecutorService threadPool = Executors.newFixedThreadPool(4);
CompletionService<String> pool = new ExecutorCompletionService<String>(threadPool);

for(int i = 0; i < 10; i++){
pool.submit(new StringTask());
}

//you have the result in the order they are completed and you don’t have to keep a
//collection of Future
for(int i = 0; i < 10; i++){
String result = pool.take().get();

//Compute the result
}
threadPool.shutdown();

See: Java Concurrency: Executors and Thread Pools

Monday, November 1, 2010

Notify and Wait

Two things to be noticed:
1) notify() and wait() need to be used inside a synchronized block. They are used for release/acquire object lock.

2) In getMessage() method, notify() is called at first beginning. It doesn't actually release the lock atm, as stated in API "Wakes up a single thread that is waiting on this object's monitor...The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object."


import java.util.Vector;

class Producer extends Thread {
static final int MAXQUEUE = 5;
private Vector messages = new Vector();

public void run() {
try {
while ( true ) {
putMessage();
sleep( 1000 );
}
}
catch( InterruptedException e ) { }
}

private synchronized void putMessage()
throws InterruptedException {

while ( messages.size() == MAXQUEUE )
wait();
messages.addElement( new java.util.Date().toString() );
notify();
}

// Called by Consumer
public synchronized String getMessage()
throws InterruptedException {
notify();
while ( messages.size() == 0 )
wait();
String message = (String)messages.firstElement();
messages.removeElement( message );
return message;
}
}

class Consumer extends Thread {
Producer producer;

Consumer(Producer p) {
producer = p;
}

public void run() {
try {
while ( true ) {
String message = producer.getMessage();
System.out.println("Got message: " + message);
sleep( 2000 );
}
}
catch( InterruptedException e ) { }
}

public static void main(String args[]) {
Producer producer = new Producer();
producer.start();
new Consumer( producer ).start();
}
}



See: Exploring Java: Threads

Monday, July 12, 2010

EventQueue & Session timeout tracking

Swing's single-threaded model make UI updates run in Event Dispatch thread. Those actionPerformed listener method of UI components already runs in Event dispatch thread. The EventQueue.invokeLater(Runnable), EventQueue.invokeAndWait(Runnable) cause runnable to have its run method called in the dispatch thread of the system EventQueue. The cases occur for long lasting task and run in separate thread (SwingWork provides convenient methods for it).

SwingUtilites is a wrapper class of EventQueue for old java code.

We could provide our custom EventQueue for System Event Queue, which contains events processed by event dispatch thread. It looks like Swing launch a new AWT-EventQueue- thread when a new EventQueue is set.


Toolkit.getDefaultToolkit().getSystemEventQueue().push(new NSEventQueue());

For custom EventQueue, we can override its dispatchEvent() method and record the keepAlive timestamp for mouse and keyboard activities. It could be used for session timeout tracking.

See: Swing threading and Dispatch thread