usr-local-ΕΨΗΕΛΩΝ
usr-local-ΕΨΗΕΛΩΝ

Reputation: 26934

Asynchronous task pattern in Java

I'm moving from C# to Java, and I need to implement a set of asynchronous tasks.

I have a good knowledge of Java threading, but I liked .NET's BeginInvoke and EndInvoke methods because they allowed me to switch from synchronous to asynchronous tasks with ease.

In my case, if I have a set of I/O intensive operations (suitable for changing to async) like the following:

DoOperation1();
DoOperation2();
DoOperation3();

in .NET I would easily do something like:

BeginInvoke(DoOperation1);
BeginInvoke(DoOperation2);
BeginInvoke(DoOperation3);
EndInvoke(Result1);
EndInvoke(Result2);
EndInvoke(Result3);

Briefly, my question is: is there anything similar in Java, or do I need to use threads manually "the old way"?

Thank you.

Upvotes: 10

Views: 5874

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504182

You probably want to use futures in Java. You submit a task to an ExecutorService and receive a Future<T> back which you can ask view in a similar way to Task<T> from the .NET 4 TPL... you can ask a future for its result in a blocking manner, or with a timeout, ask if it's done etc.

Working with Callable<T> isn't as neat as using delegates in C# via method group conversions and lambda expressions, but the basic ideas are similar.

Upvotes: 12

GaryF
GaryF

Reputation: 24370

I think you'd probably want to use ExecutorService alongside Runnable or Callable classes that wrap the implementation of the jobs you're trying to run.

An example:

SomeTask someTask1 = ...
SomeTask someTask2 = ...

executorService.execute(someTask1);
executorService.execute(someTask2);

executorService.shutdown(); //Close down the service

Upvotes: 4

Related Questions