Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 880
usr-local-ΕΨΗΕΛΩΝ Avatar asked Feb 28 '11 14:02

usr-local-ΕΨΗΕΛΩΝ


People also ask

What is an asynchronous task in Java?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .

What is asynchronous design pattern?

In multithreaded computer programming, asynchronous method invocation (AMI), also known as asynchronous method calls or the asynchronous pattern is a design pattern in which the call site is not blocked while waiting for the called code to finish. Instead, the calling thread is notified when the reply arrives.

What is task based Async model?

The Task-based Asynchronous Pattern enables developers to define asynchronous functions within a single method definition, instead of having "begin" and "end" function pairs or separate callbacks. This makes coding the asynchronous function very intuitive and clear in C# 4.5 (version next).


1 Answers

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.

like image 152
Jon Skeet Avatar answered Sep 23 '22 02:09

Jon Skeet