|
|
< Day Day Up > |
|
10.7 Single-Threaded AccessIn Chapter 7, we saw the threading restrictions placed on developers using the Swing library. Swing classes are not threadsafe, so they must always be called from a single thread. In the case of Swing, that means that they must be called from the event-dispatching thread, using the invokeLater() and invokeAndWait() methods of the SwingUtilities class. What if you have a different library that isn't threadsafe and want to use the library in your multithreaded programs? As long as you access that library from a single thread, your program won't run into any problems with data synchronization. Here's a class you can use to accomplish that: package javathreads.examples.ch10;
import java.util.concurrent.*;
import java.io.*;
public class SingleThreadAccess {
private ThreadPoolExecutor tpe;
public SingleThreadAccess( ) {
tpe = new ThreadPoolExecutor(
1, 1, 50000L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>( ));
}
public void invokeLater(Runnable r) {
tpe.execute(r);
}
public void invokeAndWait(Runnable r)
throws InterruptedException, ExecutionException {
FutureTask task = new FutureTask(r, null);
tpe.execute(task);
task.get( );
}
public void shutdown( ) {
tpe.shutdown( );
}
}The methods of this class function exactly like their counterparts in the SwingUtilities class: the invokeLater() method runs its task asynchronously and the invokeAndWait() method runs it synchronously. Because the thread pool has only a single thread, all tasks passed to the SingleThreadAccess object are executed by a single thread, regardless of how many threads use the access object: the tasks run by the SingleThreadAccess object can call thread-unsafe classes. In Chapter 9, we show the effect of running our Fibonacci calculations when the threads are serialized; our online examples for this chapter show (as example 2) how to use the SingleThreadAccess class to achieve that same behavior. |
|
|
< Day Day Up > |
|