Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created January 11, 2015 03:42
Show Gist options
  • Save adohe-zz/748f90eb8eab7bd23f23 to your computer and use it in GitHub Desktop.
Save adohe-zz/748f90eb8eab7bd23f23 to your computer and use it in GitHub Desktop.
Simple about FutureTask usage
package com.xqbase.java;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* Simple about how to use FutureTask to do some pre-load
* task.
*
* @author Tony He
*/
public class PreLoader {
private final FutureTask<ProductInfo> future =
new FutureTask<ProductInfo>(new Callable<ProductInfo>() {
@Override
public ProductInfo call() throws DataLoadException {
return loadProductInfoFromDB();
}
});
private final Thread thread = new Thread(future);
public void start() {
thread.start();
}
public ProductInfo get() throws InterruptedException {
try {
return future.get();
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof DataLoadException) {
throw (DataLoadException) cause;
} else {
throw launderThrowable(cause);
}
}
}
public static RuntimeException launderThrowable(Throwable t) {
if (t instanceof RuntimeException) {
return (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new IllegalStateException("Not unchecked", t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment