Skip to content

Instantly share code, notes, and snippets.

@phatboyg
Created March 27, 2012 03:20
Show Gist options
  • Save phatboyg/2212197 to your computer and use it in GitHub Desktop.
Save phatboyg/2212197 to your computer and use it in GitHub Desktop.
Using Java Executors for scheduling timeouts on operations
import java.util.concurrent.*;
class MyCallable implements Callable<Integer>
{
int limit;
public MyCallable(int limit)
{
this.limit = limit;
}
public Integer call()
{
try
{
for(int i = 0; i < limit; i++)
{
System.out.println("I am in it!! " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException ex)
{
System.out.println("I get it, you got tired of waiting on me");
}
catch(Exception ex){
System.out.println("Exception: " + ex.getMessage());
}
return this.limit;
}
}
public final class MyExample
{
public static final void main(String[] args)
{
System.out.println("Hello, World.");
// we need one pool to handle the cancellation of tasks, it only needs a single thread
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
// we need a worker pool to handle up to n (in this case 4) concurrent workers
ScheduledExecutorService workerPool = Executors.newScheduledThreadPool(4);
try
{
// first I'm going to submit my task
final Future<Integer> handler = workerPool.submit(new MyCallable(1));
// then i'm going to submit my cancel handler
pool.schedule(new Runnable()
{
public void run()
{
handler.cancel(true);
}
}, 2000, TimeUnit.MILLISECONDS);
// first I'm going to submit my task
final Future<Integer> handler2 = workerPool.submit(new MyCallable(4));
// then i'm going to submit my cancel handler
pool.schedule(new Runnable()
{
public void run()
{
handler2.cancel(true);
}
}, 2000, TimeUnit.MILLISECONDS);
// wait on the task to complete, if it does, we get the result
int result = handler.get();
System.out.println("Result: " + result);
int result2 = handler2.get();
System.out.println("result2 = " + result2);
}
catch(CancellationException ex)
{
System.out.println("cancelled.");
}
catch(InterruptedException ex)
{
System.out.println("interrupted");
}
catch(Exception ex)
{
System.out.println("outer ex: " + ex.getMessage());
}
pool.shutdown();
workerPool.shutdown();
while(!pool.isTerminated())
{
System.out.print(".");
}
while(!workerPool.isTerminated())
{
System.out.println(".");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment