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.
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 .
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With