The Future is here

OK, so at my job I’ve just learned about Java futures in the java.util.concurrency library.  They are pretty cool, but I’m new to them so I may be getting some things wrong.  I don’t need to instantiate huge numbers of threads anymore, but can simply use the Future object to handle it for me.  Future is an interface that contains methods to check if a computation is complete.  It kind of makes multithreading more simple.  Here’s a good tutorial: http://java.dzone.com/articles/javautilconcurrentfuture

There’s a few things that are needed when working with Futures.

1) ExecutorService or some kind of thread pooling

I think futures still use threads, and the ExecutorService helps manage them.  So instantiate an ExecutorService (import java.util.concurrent.ExecutorService;) like this:

   private final ExecutorService pool = Executors.newSingleThreadExecutor();</pre>   

2) An object of type runnable or callable that is submitted to the thread pool. This returns a Future.

@Async
private Future<String> getPreview(final ContentItem item) {
    return pool.submit(new Callable<String>() {
        @Override 
        public String call() {
              return fbPreview.generateAndStorePreview(item);
        }    
    });
 }

3) A Future object with a call of get(long timeout, TimeUnit unit)
throws InterruptedException,
ExecutionException,
TimeoutException

The get function, according to the javadoc states that it “Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.”

Future<String> f = getPreview(item);

try {
   String url = f.get(30000, TimeUnit.MILLISECONDS);
   System.out.println("Preview generated at " + url);
} catch (TimeoutException te) {
   log.error("Facebook Preview generation for item: ? timed out. Continuing to error screen.", item.getId());
} catch (ExecutionException ee) {
   log.error("Facebook Preview generation for item: ? erred in execution. Continuing to error screen.", item.getId()); 
} catch (Exception e) {
   log.error("Facebook Preview generation for item: ? erred. Continuing to error screen.", item.getId());
}

So all in all, this is a way of doing some nifty threading without actually having to use threads and manage resources.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s