Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a Future<MyObject> without using ExecutorService?

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 ?

like image 503
krosenvold Avatar asked May 08 '09 11:05

krosenvold


People also ask

Can I use Callable thread without ExecutorService?

Yes you can use the call() method of a Callable or the run() method of a Runnable from your own thread directly.

How do I stop being an ExecutorService?

To properly shut down an ExecutorService, we have the shutdown() and shutdownNow() APIs. The shutdown() method doesn't cause immediate destruction of the ExecutorService. It will make the ExecutorService stop accepting new tasks and shut down after all running threads finish their current work: executorService.

Why do we need ExecutorService?

ExecutorService abstracts away many of the complexities associated with the lower-level abstractions like raw Thread . It provides mechanisms for safely starting, closing down, submitting, executing, and blocking on the successful or abrupt termination of tasks (expressed as Runnable or Callable ).

Can you give an example for ExecutorService?

Here is an example of executing a Runnable with an ExecutorService : ExecutorService executorService = Executors. newSingleThreadExecutor(); executorService. execute(new Runnable() { public void run() { System.


1 Answers

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.

like image 138
alphazero Avatar answered Oct 28 '22 03:10

alphazero