I have One Callable which I invoked using
FutureTask<Integer> task = new FutureTask<Integer>(new MyCallable(name, type));
pool = Executors.newSingleThreadExecutor();
pool.submit(task);
I want to know Is execution is continue after pool.submit(task) or It will wait for callable to complete its execution?
In short I just want to know is there any method like thread.join() for Callable?
... is there any method like thread.join() for Callable?
The pool.submit(callable) method returns a Future and will start executing immediately if the threads are available in the pool. To do a join, you can call future.get() which joins with the thread, returning the value returned by the call() method. It is important to note that get() may throw an ExecutionException if the call() method threw.
You do not need to wrap your Callable in a FutureTask. The thread-pool does that for you. So your code would be:
pool = Executors.newSingleThreadExecutor();
Future<String> future = pool.submit(new MyCallable(name, type));
// now you can do something in the foreground as your callable runs in the back
// when you are ready to get the background task's result you call get()
// get() waits for the callable to return with the value from call
// it also may throw an exception if the call() method threw
String value = future.get();
This is if your MyCallable implements Callable<String> of course. The Future<?> will match whatever type your Callable is.
task.get() (task being a FutureTask) expects the current thread to wait for the completion of the managed task by the thread pooler.
This method ends up returning either a concrete result or throwing the same checked exception (although wrapped into an ExecutionException) that the job thread would throw during its task.
Related
In C++ you can start a thread with a deferred or asynchronous launch policy. Is there a way to replicate this functionality in Java?
auto T1 = std::async(std::launch::deferred, doSomething());
auto T2 = std::async(std::launch::async, doSomething());
Descriptions of each--
Asynchronous:
If the async flag is set, then async executes the callable object f on a new thread of execution (with all thread-locals initialized) except that if the function f returns a value or throws an exception, it is stored in the shared state accessible through the std::future that async returns to the caller.
Deferred:
If the deferred flag is set, then async converts f and args... the same way as by std::thread constructor, but does not spawn a new thread of execution. Instead, lazy evaluation is performed: the first call to a non-timed wait function on the std::future that async returned to the caller will cause the copy of f to be invoked (as an rvalue) with the copies of args... (also passed as rvalues) in the current thread (which does not have to be the thread that originally called std::async). The result or exception is placed in the shared state associated with the future and only then it is made ready. All further accesses to the same std::future will return the result immediately.
See the documentation for details.
Future
First of all, we have to observe that std::async is a tool to execute a given task and return a std::future object that holds the result of the computation once its available.
For example we can call result.get() to block and wait for the result to arrive. Also, when the computation encountered an exception, it will be stored and rethrown to us as soon as we call result.get().
Java provides similar classes, the interface is Future and the most relevant implementation is CompletableFuture.
std::future#get translates roughly to Future#get. Even the exceptional behavior is very similar. While C++ rethrows the exception upon calling get, Java will throw a ExecutionException which has the original exception set as cause.
How to obtain a Future?
In C++ you create your future object using std::async. In Java you could use one of the many static helper methods in CompletableFuture. In your case, the most relevant are
CompletableFuture#runAsync, if the task does not return any result and
CompletableFuture#supplyAsync, if the task will return a result upon completion
So in order to create a future that just prints Hello World!, you could for example do
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> System.out.println("Hello World!"));
/*...*/
task.get();
Java not only has lambdas but also method references. Lets say you have a method that computes a heavy math task:
class MyMath {
static int compute() {
// Very heavy, duh
return (int) Math.pow(2, 5);
}
}
Then you could create a future that returns the result once its available as
CompletableFuture<Integer> task = CompletableFuture.runAsync(MyMath::compute);
/*...*/
Integer result = task.get();
async vs deferred
In C++, you have the option to specify a launch policy which dictates the threading behavior for the task. Let us put the memory promises C++ makes aside, because in Java you do not have that much control over memory.
The differences are that async will immediately schedule creation of a thread and execute the task in that thread. The result will be available at some point and is computed while you can continue work in your main task. The exact details whether it is a new thread or a cached thread depend on the compiler and are not specified.
deferred behaves completely different to that. Basically nothing happens when you call std::async, no extra thread will be created and the task will not be computed yet. The result will not be made available in the meantime at all. However, as soon as you call get, the task will be computed in your current thread and return a result. Basically as if you would have called the method directly yourself, without any async utilities at all.
std::launch::async in Java
That said, lets focus on how to translate this behavior to Java. Lets start with async.
This is the simple one, as it is basically the default and intended behavior offered in CompletableFuture. So you just do runAsync or supplyAsync, depending on whether your method returns a result or not. Let me show the previous examples again:
// without result
CompletableFuture<Void> task = CompletableFuture.runAsync(() -> System.out.println("Hello World!"));
/*...*/ // the task is computed in the meantime in a different thread
task.get();
// with result
CompletableFuture<Integer> task = CompletableFuture.supplyAsync(MyMath::compute);
/*...*/
Integer result = task.get();
Note that there are also overloads of the methods that except an Executor which can be used if you have your own thread pool and want CompletableFuture to use that instead of its own (see here for more details).
std::launch::deferred in Java
I tried around a lot to mock this behavior with CompletableFuture but it does not seem to be possibly without creating your own implementation (please correct me if I am wrong though). No matter what, it either executes directly upon creation or not at all.
So I would just propose to use the underlying task interface that you gave to CompletableFuture, for example Runnable or Supplier, directly. In our case, we might also use IntSupplier to avoid the autoboxing.
Here are the two code examples again, but this time with deferred behavior:
// without result
Runnable task = () -> System.out.println("Hello World!");
/*...*/ // the task is not computed in the meantime, no threads involved
task.run(); // the task is computed now
// with result
IntSupplier task = MyMath::compute;
/*...*/
int result = task.getAsInt();
Modern multithreading in Java
As a final note I would like to give you a better idea how multithreading is typically used in Java nowadays. The provided facilities are much richer than what C++ offers by default.
Ideally should design your system in a way that you do not have to care about such little threading details. You create an automatically managed dynamic thread pool using Executors and then launch your initial task against that (or use the default executor service provided by CompletableFuture). After that, you just setup an operation pipeline on the future object, similar to the Stream API and then just wait on the final future object.
For example, let us suppose you have a list of file names List<String> fileNames and you want to
read the file
validate its content, skip it if its invalid
compress the file
upload the file to some web server
check the response status code
and count how many where invalid, not successfull and successfull. Suppose you have some methods like
class FileUploader {
static byte[] readFile(String name) { /*...*/ }
static byte[] requireValid(byte[] content) throws IllegalStateException { /*...*/ }
static byte[] compressContent(byte[] content) { /*...*/ }
static int uploadContent(byte[] content) { /*...*/ }
}
then we can do so easily by
AtomicInteger successfull = new AtomicInteger();
AtomicInteger notSuccessfull = new AtomicInteger();
AtomicInteger invalid = new AtomicInteger();
// Setup the pipeline
List<CompletableFuture<Void>> tasks = fileNames.stream()
.map(name -> CompletableFuture
.completedFuture(name)
.thenApplyAsync(FileUploader::readFile)
.thenApplyAsync(FileUploader::requireValid)
.thenApplyAsync(FileUploader::compressContent)
.thenApplyAsync(FileUploader::uploadContent)
.handleAsync((statusCode, exception) -> {
AtomicInteger counter;
if (exception == null) {
counter = statusCode == 200 ? successfull : notSuccessfull;
} else {
counter = invalid;
}
counter.incrementAndGet();
})
).collect(Collectors.toList());
// Wait until all tasks are done
tasks.forEach(CompletableFuture::join);
// Print the results
System.out.printf("Successfull %d, not successfull %d, invalid %d%n", successfull.get(), notSuccessfull.get(), invalid.get());
The huge benefit of this is that it will reach max throughput and use all hardware capacity offered by your system. All tasks are executed completely dynamic and independent, managed by an automatic pool of threads. And you just wait until everything is done.
For asynchronous launch of a thread, in modern Java prefer the use of a high-level java.util.concurrent.ExecutorService.
One way to obtain an ExecutorService is through java.util.concurrent.Executors. Different behaviors are available for ExecutorServices; the Executors class provides methods for some common cases.
Once you have an ExecutorService, you can submit Runnables and Callables to it.
Future<MyReturnValue> myFuture = myExecutorService.submit(myTask);
If I understood you correctly, may be something like this:
private static CompletableFuture<Void> deferred(Runnable run) {
CompletableFuture<Void> future = new CompletableFuture<>();
future.thenRun(run);
return future;
}
private static CompletableFuture<Void> async(Runnable run) {
return CompletableFuture.runAsync(run);
}
And then using them like:
public static void main(String[] args) throws Exception {
CompletableFuture<Void> def = deferred(() -> System.out.println("run"));
def.complete(null);
System.out.println(def.join());
CompletableFuture<Void> async = async(() -> System.out.println("run async"));
async.join();
}
To get something like a deferred thread, you might try running a thread at a reduced priority.
First, in Java it's often idiomatic to make a task using a Runnable first. You can also use the Callable<T> interface, which allows the thread to return a value (Runnable can't).
public class MyTask implements Runnable {
#Override
public void run() {
System.out.println( "hello thread." );
}
}
Then just create a thread. In Java threads normally wrap the task they execute.
MyTask myTask = new MyTask();
Thread t = new Tread( myTask );
t.setPriority( Thread.currentThread().getPriority()-1 );
t.start();
This should not run until there is a core available to do so, which means it shouldn't run until the current thread is blocked or run out of things to do. However you're at the mercy of the OS scheduler here, so the specific operation is not guaranteed. Most OSs will guarantee that all threads run eventually, so if the current thread takes a long time with out blocking the OSs will start it executing anyway.
setPriority() can throw a security exception if you're not allowed to set the priority of a thread (uncommon but possible). So just be aware of that minor inconvenience.
For an asynch task with a Future I would use an executor service. The helper methods in the class Executors are a convenient way to do this.
First make your task as before.
public class MyCallable implements Callable<String> {
#Override
public String call() {
return "hello future thread.";
}
}
Then use an executor service to run it:
MyCallable myCallable = new MyCallable();
ExecutorService es = Executors.newCachedThreadPool();
Future<String> f = es.submit( myCallable );
You can use the Future object to query the thread, determine its running status and get the value it returns. You will need to shutdown the executor to stop all of its threads before exiting the JVM.
es.shutdown();
I've tried to write this code as simply as possible, without the use of lambdas or clever use of generics. The above should show you what those lambdas are actually implementing. However it's usually considered better to be a bit more sophisticated when writing code (and a bit less verbose) so you should investigate other syntax once you feel you understand the above.
invokeAll() doesn't return until all the Callables in the submitted Collection have completed, so what is the reason for making the results Futures?
Because the task might terminate normally or exceptionally, Futures can wrap the exception for you. For example,
Callable<Integer> c1 = () -> 1;
Callable<Integer> c2 = () -> {
throw new RuntimeException();
};
List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(c1,c2));
for (Future<Integer> future : futures) {
System.out.println(future.get());
}
Note that because of Future, we were able to get a result of the future that terminated normally and the that terminated exceptionally.
If invokeAll returned a List<T>, it would have to return those that completed successfully and discarded those with exceptions.
Checking the ExecutorService#invokeAll Javadoc
Executes the given tasks, returning a list of Futures holding their
status and results when all complete. Future.isDone() is true for each
element of the returned list. Note that a completed task could have
terminated either normally or by throwing an exception. The results
of this method are undefined if the given collection is modified while
this operation is in progress.
Means that we're getting a list of Future objects because there may be situations where we do not get a value even if the task is complete.
How does Java's Future.get() behave in the case where it is called multiple times after the task is completed?
Does it return the the same result? Or does throw an ExecutionException again and again with the same exception if the computation failed?
I can not find anything in the docs about it!
You can call get() on a Future as often as you like, and it will only block if the task that produces the result has not finished yet.
If the task has already finished, it will just immediately return the result of the task.
If the task has failed with an exception, calling get() will throw an ExecutionException each time you call it.
I can not find anything in the docs about it!
Have you read them ? because when I read them I got the Answer and here it is ....
V get()
throws InterruptedException,
ExecutionException
Waits if necessary for the computation to complete, and then retrieves
its result.
Returns:
the computed result
Throws:
CancellationException - if the computation was cancelled
ExecutionException - if the computation threw an exception
InterruptedException - if the current thread was interrupted while waiting
If Computation is not completed it will wait , and if it has already completed it will return result ASAP , no matter how many times you call it
Given this code,
Collection<?> callables = ...
ExecutorService executorService = ...
List<Future<?>> futures = executorService.invokeAll(callables, TIMEOUT, TimeUnit.SECONDS);
I'd like to know which of the callables were cancelled (did not finish in time). I know I can query each Future with .isCancelled() but that gives me no information as to which exact Callable was cancelled.
One solution would be for Future to implement a toString() method that delegates to the underlying toString() of Callable. Unfortunately, this is not done.
I know I can query each Future with .isCancelled() but that gives me no information as to which exact Callable was cancelled.
The list of Futures is in the same order as the list of Callables it was created from. So you can keep track that way.
I have made a multi-threading program. In it, the main thread starts 10 threads but the problem is whenever an exception occured in one of the threads, the whole application gets stopped.
But I want that whenever an exception occurred in one thread, only that thread should gets stopped and other threads keep working. How can I do that?
Second, I want that the main thread should stopped only after all the 10 threads finished. How can I do that?
You could use an ExecutorService (containing multiple threads) to process your individual items of work by calling submit(). The submit method returns a Future, which will encapsulate either the result of the processing or any exception thrown. In other words, the threads within your ExecutorService will not terminate if an exception occurs.
Example
First create an executor service containing more than one thread:
ExecutorService execService = Executors.newFixedThreadPool(5);
Define the item of work we wish to submit as a Callable:
public class MyWorkItem implements Callable<Integer> {
public Integer call() throws Exception {
int result = new Random().nextInt(5);
// Randomly fail.
if (result == 0) {
throw new IllegalArgumentException("Fail!");
}
return result;
}
}
Submit some work for the executor service to do, and store the Future<Integer> for each Callable<Integer>.
List<Future<Integer>> futures = new LinkedList<Future<Integer>>();
for (int i=0; i<10; ++i) {
futures.add(execService.submit(new MyWorkItem()));
}
Now iterate over the futures attempting to retrieve the result of each work item (we could use a CompletionService for this).
for (Future<Integer> future : futures) {
try {
Integer result = future.get();
} catch(Exception ex) {
// Handle exception.
}
}
At the end of your main method you should call join on every started thread.
By the way: If you want to handle the exceptions of your threads, you can use Thread.setDefaultUncaughtExceptionHandler()
Surround with try/catch all
public void run() {
try {
....
} catch( Exception e ){}
}
Although I would better try to identify the reasons for those exceptions.
For #1, if this is your intended goal you should consider how you are handling that exception and what types of exceptions your are expecting. If these are application faults you can determine a more useful way to catch the exception at the individual thread level and feed and important information back to the parent thread. Alternatively a solution for managing the thread pool for you may be a better method to go with as #Adamski pointed out, like the implementation of the ExecutorSerivce ThreadPoolExecutor, however you will need to understand the exceptions and if they can be prevented with some additional logic if not then having a better way to manage your jobs effectively is the way to go.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html
For #2, join() or use a Thread pool to manage them.
Concerning your first point I would suggest that you gracefully exit a thread when an exception is thrown, that is, catch it within the thread (and not let it bubble up to the jvm).