views:

193

answers:

3

I would really like to do something like this:

 Callable<MyObject> myCallable = ....
 Future<MyObject> = new Thread( myCallable).start();

I basically want to start a single long-running task that runs in parallel with my main task, and I do not want pooling or thread re-use. The Executors stuff seems to be very pooling oriented and it requires me to shut down the pool, all of which I don't want to do.

I want to use the "Callable/Future" pattern because I may later have to introduce Executors, but as things currently stand they're just overhead.

Any suggestions ?

+5  A: 

Well, you can fairly easily write a helper method:

public static Future<T> createFuture(Callable<T> callable)
{
    ExecutorService service = Executors.newSingleThreadExecutor();
    Future<T> ret = service.submit(callable);
    // Let the thread die when the callable has finished
    service.shutdown();
    return ret;
}

EDIT: To expand on alphazero's answer, you'd use FutureTask like this:

FutureTask<MyObject> future = new FutureTask<MyObject>(myCallable);
new Thread(future).start(); // FutureTask implements Runnable
// Now use the future however you want

And yes, I'd say this is nicer than my first answer :)

Jon Skeet
+5  A: 

Try FutureTask. It doesn't have any explicit dependency on the Executor framework and can be instantiated as is, or you can extend it to customize it.

A: 

The callable/future stuff is based around thread pooling. If you need to do the same operation many times, I would strongly recommend using a pool.

If you do not want to use a thread pool, then I would suggest using a thread manually. It is not hard to do what you want by using a single thread and joining on it.

class X extends Thread {
   MyObject result;

   public void run() {
      // .. do the operation here. Set result
   }

   public MyObject getResult() {
      // This will block until the thread is complete
      join();
      return result;
   }
}

To run this call:

X x = new X();
x.start();

eventually you will call getResult which will block until X's thread is complete:

x.getResult();
Chris Dail