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.
You probably want to use futures in Java. You submit a task to an
ExecutorServiceand receive aFuture<T>back which you can ask view in a similar way toTask<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.