Skip to content

Instantly share code, notes, and snippets.

@hoffrocket
Created March 29, 2013 16:24
Show Gist options
  • Save hoffrocket/5271903 to your computer and use it in GitHub Desktop.
Save hoffrocket/5271903 to your computer and use it in GitHub Desktop.
demonstrate livelock on java ThreadPoolExecutor
package jon;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class LiveLockExample {
public static void main(String[] args) throws Exception {
final ExecutorService pool = Executors.newFixedThreadPool(1);
runLiveLock(pool);
pool.shutdownNow();
final ForkJoinPool fjPool = new ForkJoinPool(1);
runLiveLock(fjPool);
fjPool.shutdownNow();
}
private static void runLiveLock(final ExecutorService pool) throws InterruptedException, ExecutionException {
Future<Void> outerFuture = pool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println("Pre submit on outer thread " + Thread.currentThread().getName());
Future<Void> innerFuture = pool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println("Inner call on thread " + Thread.currentThread().getName());
return null;
}
});
innerFuture.get();
System.out.println("Post submit on outer thread " + Thread.currentThread().getName());
return null;
}
});
try {
outerFuture.get(3, TimeUnit.SECONDS);
} catch (TimeoutException e) {
System.out.println("FAILED: Got a timeout waiting for outerFuture");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment