java.util.concurrent.Future.get() not returning - java

I have the following Java code:
final Future future = exeService.submit(
new Runnable() {
public void run() {
myObject.doSomething();
}
}
);
future.get();
where exeService is an instance of
java.util.concurrent.ExecutorService
The problem is that myObject.doSomething() never returns, and, hence, future.get() never returns.
However, if I replace the call to submit with a call to execute like this:
exeService.execute(
new Runnable() {
public void run() {
myObject.doSomething();
}
}
);
the call to myObject.doSomething() does return. I don't know if it matters, but doSomething() is a void method.
Why is doSomething() finishing when using execute but not when using submit?
Also, I don't need to use Future.get(); that just seemed to be the most natural way of doing this. (I also run into the same problem with CountdownLatch.) The point is that I need to wait for doSomething() to finish before proceeding, and, for complicated reasons I won't go into here, I need to launch it on a separate thread. If there is another way of doing this that works, that would be fine.

As in Executor.execute() Javadoc:
Executes the given command at some
time in the future. The command may
execute in a new thread, in a pooled
thread, or in the calling thread, at
the discretion of the Executor
implementation.
So, the method execute() returns immediately leaving you with no option to query to status of submitted task.
On the other hand ExecutorService.submit():
Submits a Runnable task for execution
and returns a Future representing that
task. The Future's get method will
return null upon successful
completion.
The Future.get() will return only after successful competion, so never in your case.
This is further noted in Future.get() documentation:
Waits if necessary for the computation
to complete, and then retrieves its
result.

I created an SSCCE:
package com.stackoverflow.q2585971;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Test {
public static void main(String args[]) throws Exception {
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> future = executor.submit(
new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Epic fail.");
}
}
}
);
System.out.println("Waiting for task to finish..");
future.get();
System.out.println("Task finished!");
executor.shutdown();
}
}
It works perfectly fine. It first prints
Waiting for task to finish..
then after one second you see
Task finished!
So, your problem lies somewhere else. I'll duplicate my comment on your question here:
Your question is pretty confusing. The first construct should just work. The confusion is in "returning". Don't you just mean "finishing" or "executing"? Your confusion seems to be based on the fact that future.get() actually waits for the runnable to be finished and thus will block the thread and prevent it from executing the remnant of the code after the future.get() line.

Java futures are blocking! get(). This method blocks the current thread until a future instance completes its work, thus requiring the use of one thread more than the work that must be performed just to manage what happens when it is done

Check for a deadlock(s) in doSomething.
I would start with searching for wait calls.
If you wait for something, you need to signal the object you are waiting for from the other thread by calling notify or notifyAll.

Related

Stopping a thread in an executor service

I am faced with a situation where I need to stop a thread of Executor service from running.
I have already read the solution in other posts which says to make use of Future object and cancel the task.
But I rather tried a different approach.
Please can anyone let me know if there is any issue with this approach.
Following is my Runnable class.
public class TestRunnable implements Runnable {
Thread t;
#Override
public void run() {
// TODO Auto-generated method stub
setT(Thread.currentThread());
while(true)
{
if(Thread.currentThread().isInterrupted())
{
System.out.println("From Inside thread, Exiting");
System.exit(0);
}
}
}
public void setT(Thread t) {
this.t = t;
}
public Thread getT() {
return t;
}
}
Following is my main method:
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ruunTest {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
ExecutorService service = Executors.newCachedThreadPool();
TestRunnable test = new TestRunnable();
service.execute(test);
Thread.sleep(1000);
System.out.println("About to Interrupt");
test.getT().interrupt();
}
}
The only proper way to do this is to cancel the Future corresponding to your task and in your task, you should check regularly if the thread has been interrupted or not.
Something like that:
public class Task implements Callable<Void> {
#Override
public Void call() throws InterruptedException {
while(true) {
// Check regularly in your code if the thread has been
// interrupted and if so throws an exception to stop
// the task immediately
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread interrupted");
}
}
}
}
Then your main code would be:
ExecutorService service = Executors.newCachedThreadPool();
// My task
Task task = new Task();
// Submit the task and get the corresponding future
Future<?> future = service.submit(task);
...
// Cancel the task which will interrupt the thread that was executing the
// task if any
future.cancel(true);
Not a good idea to stop a thread voluntarily. Your code is not stopping a thread it actually blocking the whole JVM form progressing further. You actually are missing the whole point of the executor service.
The ideology of the executor is that 'I' have an expanding / contracting list of threads that will do the work for you. 'You' just give me individual, mutually exclusive work jobs to action (Runnables or Callables). The main point to understand here is "you don't worry about threads and their life cycle" ... you just create work items and give them to me to execute. If you don't want to execute a work or want to stop in middle call the cancel method, else don't worry about it, because once its done 'I' will finish and clean up and provide you the return values if any.
'I' will also manage the thread pool for you but expanding it with more threads when work jobs come in faster and contracting it to lesser threads by "closing idle threads" when jobs are less frequently pouring in.
Now tell me, is it right what you are trying to achieve.
You can use Quasar library for threads, works faster that Java native threads and are easier to use.
http://www.paralleluniverse.co/quasar/
Try to thread.interrupt() but it is not recommended.
You can use thread.stop , although it will throw threadDeathError which needs to be handled.
If you use future.cancel, it will cancel the task but wont kill the thread as thread will go back to thread pool. Thread.stop will kill the thread.

Interrupt Thread in java

I have a situation where I'm using a Thread, she call a method that will do multiple processes, I need to use a "cancel" button in which you have to stop the thread, I not can use: "while" ,to verify that it was canceled because it not has loop in this process.
Ex:
Task<Void> task = new Task<Void>() {
#Override
protected Void call() throws Exception {
controller = new FirstEtapaController();
execProcess();
return null;
}
};
new Thread(task).start();
Call Method
private void execProcess() {
Thread thread = new Thread(new Runnable() {
public void run() {
getController().execMhetod();
refreshTable();
}
});
thread.start();
thread.join();
};
Ie, I need to stop this process, even when the "ExecMethod" already running, it will take minutes, so I've gotta stop it and not have to wait for him to finish so that , others do not continues.
Remembering that this process will do iteration with my DAO.
The only way (well behaved way) is to add logic points in you spawned threads to check for an interrupted state. You can choose to use the built-in Thread.interrupt() mechanisms, or add your own logic using some form of thread-safe variable (an AtomicBoolean?) or a Semaphore of some sort.
If you use the Thread.interrupt() then your child processes will throw an InterruptedException when they encounter certain conditions, like Thread.wait() and other methods which require synchronization or use the java.util.concurrent.* classes.
You will need to (should already be) handle the InterruptedExceptions in the threads anyway, but perhaps you will need to put regular 'checks' in your child processes to look for the interrupted state anyway (can use Thread.isInterrupted() )
It is worth reading this Handling InterruptedException in Java
If instead of a raw Thread if you use an ExecutorService you'll end up with lots of additional methods/levers to control your threads, one of which is shutdownAll() which uses Thread.interrupt() to kill your thread and lets you check thread status via isTerminated()
Your user interface does not have to wait for the worker thread to finish, so don't worry too much about that.
Alas, Thread.destroy() and Thread.stop() are deprecated, due to bad implementations. I don't think there is a good "sig-kill" type of substitute for Java threads. You are going to have to recode the worker to check an abort flag of some kind, if it matters much. Otherwise, just let it waste a little CPU. ("you can't cancel that Save -- I've already done it!", in effect)
Whether or not a task can be canceled really depends on its implementation. Typically it intermittently checks a flag whether it should continue or not.
You can implement such a flag yourself, and a method to set it :
private volatile boolean shouldStop;
public void cancel() {
shouldStop = true;
}
#Override
public void run() {
while (!shouldStop) {
// do work
}
}
But threads already come with a flag : the interrupted flag. And while it is not necessarily used for canceling a thread, it is typical to use it for exactly that purpose. In fact the standard ExecutorService implementations will try to cancel their threads by interrupting them.
Aside from that several blocking methods (methods that put a thread in BLOCKED or WAITING state) will throw an InterruptedException when the thread is interrupted, at which point they become RUNNABLE again. This is something the previous approach with a boolean flag cannot achieve.
Therefore it is a better approach to use interruption to allow a task to be canceled. And you do not really need that cancel() method any more either :
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// do work
}
}
As a bonus, any code that knows your thread, knows how to cancel it. Including standard ExecutorService implementations.
Care should be taken when catching an InterruptedException, since doing that clears the interrupted flag. It is adviseable to always restore the interrupted flag when catching the Exception, so clients also know it's time to stop doing what they're doing.
private BlockingQueue<Integer> queue;
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Integer id = queue.take(); // blocking method
// do work
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
To cancel a thread, you can simply keep a reference to the Thread object and call interrupt() on it :
Thread thread = new Thread(new InterruptibleTask());
thread.start();
// some time after :
thread.interrupt();
But a more elegant approach is keeping tabs on your task (and not so much the specific thread it runs on) through a Future object. You can do this by wrapping your Runnable or Callable in a FutureTask.
RunnableFuture<Void> task = new FutureTask<>(new InterruptibleTask(), null);
new Thread(task).start();
// some time after :
task.cancel(true); // true indicating interruption may be used to cancel.
A Future is key in controlling your task. It allows you to wait for its completion, and optionally receive a value the task calculated :
try {
String value = future.get(); // return value is generically typed String is just as example.
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // since future.get() blocks
} catch (ExecutionException e) {
logger.log(Level.SEVERE, "Exception on worker thread", e.getCause()); // the ExecutionException's cause is the Exception that occurred in the Task
}
If you have several tasks (or even just one) it is worth using an ExecutorService :
ExecutorService pool = Executors.newCachedThreadPool();
Future<?> submit = pool.submit(new InterruptibleTask());
pool.shutdownNow(); // depending on ExecutorService implementation this will cancel all tasks for you, the ones Executors returns do.

Implement timeout in Java 1.4

I can not use Executor and Future for trapping TimeOutException as it is 1.4
I need to timeout after 30 seconds if method is not complete.
//Caller class
public static void main() {
EJBMethod() // has to timeout after 30 seconds
}
//EJB method in some other class
public void EJBMethod() {
}
An approach that I am thinking is to wrap this method call in a Runnable and set some volatile boolean from run() after method is over. THen , in caller, we can sleep for 30 seconds after calling that method and once woke up, I will check the boolean in caller if it is SET. If not set, then we need to stop that thread.
In the simplest case, you could just go with a Thread + an arbitrary Runnable.
If you want to make the call blocking from the perspective of the caller, you can create a "service" class that runs a worker thread and uses Thread.join(long) to wait for the operation to complete or abandon it after the specified timeout (Pay special attention to the proper handling of InterruptedException so things don't get messed up).
Thread.isAlive() will tell you whether the Thread finished or not.
Retrieving the result is a separate concern; I guess you can deal with that...
[EDIT]
Quick-and-dirty example (do not use in production as is!):
/**
* Actually needs some refactoring
* Also, did not verify for atomicity - should be redesigned
*/
public V theServiceCall(final T param) {
final MyResultBuffer<V> buffer = new MyResultBuffer<V>();
Runnable task = new Runnable() {
public void run() {
V result = ejb.process(param);
buffer.putResult(result);
}
}
Thread t = new Thread(task);
t.setDaemon(true);
t.start();
try {
t.join(TASK_TIMEOUT_MILLIS);
} catch (InterruptedException e) {
// Handle it as needed (current thread is probably asked to terminate)
}
return (t.isAlive()) ? null : buffer.getResult();
}
NOTE: Instead of Thread.setDaemon() you can implement a shutdown flag in your Runnable as it would be a better solution.
[/EDIT]

Properly writing task that ExecutorService.shutdownNow() can stop?

I have a processing loop of the form
while (true) {
doWork();
Thread.sleep(SLEEP_INTERVAL);
}
I want to make a Runnable out of this that can play well with ExecutorService and which will exit when ExecutorService.shutdownNow() is called.
I'm looking to write it this way:
public WorkerTask implements Runnable
{
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
doWork();
try {
Thread.sleep(SLEEP_INTERVAL);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
Simple testing shows it at least appearing to work in that the task gets interrupted and will exit and the ExecutorService will shut down, and appears to do so whether the interrupt arrives while doWork() is processing or during the sleep. (By varying how much work doWork() does and how big SLEEP_INTERVAL is I can pretty much control where the interrupt happens).
But when I google I see examples using Thread.interrupted() as well as Thread.currentThread().isInterrupted(). I understand that the former clears the interrupted flag while the latter leaves it, but is there any other difference I need to care about?
I also see versions where the result of Thread.currentThread().isInterrupted() or Thread.interrupted() is stored in a volatile variable and that variable is used as the while loop test condition. Is that just a style or is there a need to do that? In what I've written do I have to worry that somehow something can clear the interrupt flag between when it is set (whether by being received when the thread is live, or by my catching InterruptedException and reasserting the flag) and when Thread.currentThread().isInterrupted() is called in the loop test?
Your code looks fine to me. Introducing an additional volatile variable would be unnecessary complexity: the interrupt status does the job.
The recommended way, in Java Concurrency in Practice, to deal with interrupts in tasks is to either throw an InterruptedException (this is doable if the task is a Callable and not a Runnable), or to make sure the interrupt status is set and to exit from the task ASAP. Your code does that well.
Could you take a look at ScheduledExecutorService if it matches your requirements:
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}}
Basically you should take advantage of java.util.concurrent libraries here .You should submit your task via ExecutorService.submit()and then call blocking methods like Future.get() , then you can be sure that those methods will respond to interruption as soon as possible by throwing an ExecutionException() .You probably should get rid of that Thread.sleep() since it is doing nothing . You want to sniff an interrupt as quickly as possible .You possibly also want to wait for a timeout in case your task is doing something inifinitely . So if the task terminates with a TimeOutException , the task is cancelled via its Future.
I call cancel() unconditionally since cancelling a completed task has no effect.
In that case you can do some thing like :
public static void main(String[] args) {
WorkerTask runnable;
TimeUnit unit;
Future<?> task = executor.submit(workerTask);
try{
task.get(timeout,unit);
} catch(TimeoutException e){
}catch(ExecutionException e){
throw e.getCause();
} finally{
//Harmless if the task already completed
task.cancel(true);
}
}
}

Choose between ExecutorService's submit and ExecutorService's execute

How should I choose between ExecutorService's submit or execute, if the returned value is not my concern?
If I test both, I didn't see any differences among the two except the returned value.
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(new Task());
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(new Task());
There is a difference concerning exception/error handling.
A task queued with execute() that generates some Throwable will cause the UncaughtExceptionHandler for the Thread running the task to be invoked. The default UncaughtExceptionHandler, which typically prints the Throwable stack trace to System.err, will be invoked if no custom handler has been installed.
On the other hand, a Throwable generated by a task queued with submit() will bind the Throwable to the Future that was produced from the call to submit(). Calling get() on that Future will throw an ExecutionException with the original Throwable as its cause (accessible by calling getCause() on the ExecutionException).
execute: Use it for fire and forget calls
submit: Use it to inspect the result of method call and take appropriate action on Future objected returned by the call
From javadocs
submit(Callable<T> task)
Submits a value-returning task for execution and returns a Future
representing the pending results of the task.
Future<?> submit(Runnable task)
Submits a Runnable task for execution and returns a Future representing that
task.
void execute(Runnable command)
Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.
You have to take precaution while using submit(). It hides exception in the framework itself unless you embed your task code in try{} catch{} block.
Example code: This code swallows Arithmetic exception : / by zero.
import java.util.concurrent.*;
import java.util.*;
public class ExecuteSubmitDemo{
public ExecuteSubmitDemo()
{
System.out.println("creating service");
ExecutorService service = Executors.newFixedThreadPool(10);
//ExtendedExecutor service = new ExtendedExecutor();
service.submit(new Runnable(){
public void run(){
int a=4, b = 0;
System.out.println("a and b="+a+":"+b);
System.out.println("a/b:"+(a/b));
System.out.println("Thread Name in Runnable after divide by zero:"+Thread.currentThread().getName());
}
});
service.shutdown();
}
public static void main(String args[]){
ExecuteSubmitDemo demo = new ExecuteSubmitDemo();
}
}
output:
java ExecuteSubmitDemo
creating service
a and b=4:0
Same code throws by replacing submit() with execute() :
Replace
service.submit(new Runnable(){
with
service.execute(new Runnable(){
output:
java ExecuteSubmitDemo
creating service
a and b=4:0
Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
at ExecuteSubmitDemo$1.run(ExecuteSubmitDemo.java:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
How to handle the these type of scenarios while using submit()?
Embed your Task code ( Either Runnable or Callable implementation) with try{} catch{} block code
Implement CustomThreadPoolExecutor
New solution:
import java.util.concurrent.*;
import java.util.*;
public class ExecuteSubmitDemo{
public ExecuteSubmitDemo()
{
System.out.println("creating service");
//ExecutorService service = Executors.newFixedThreadPool(10);
ExtendedExecutor service = new ExtendedExecutor();
service.submit(new Runnable(){
public void run(){
int a=4, b = 0;
System.out.println("a and b="+a+":"+b);
System.out.println("a/b:"+(a/b));
System.out.println("Thread Name in Runnable after divide by zero:"+Thread.currentThread().getName());
}
});
service.shutdown();
}
public static void main(String args[]){
ExecuteSubmitDemo demo = new ExecuteSubmitDemo();
}
}
class ExtendedExecutor extends ThreadPoolExecutor {
public ExtendedExecutor() {
super(1,1,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(100));
}
// ...
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
System.out.println(t);
}
}
output:
java ExecuteSubmitDemo
creating service
a and b=4:0
java.lang.ArithmeticException: / by zero
if you dont care about the return type, use execute. it's the same as submit, just without the return of Future.
Taken from the Javadoc:
Method submit extends base method {#link Executor#execute} by creating and
returning a {#link Future} that can be used to cancel execution and/or wait for
completion.
Personally I prefer the use of execute because it feels more declarative, although this really is a matter of personal preference.
To give more information: in the case of the ExecutorService implementation, the core implementation being returned by the call to Executors.newSingleThreadedExecutor() is a ThreadPoolExecutor.
The submit calls are provided by its parent AbstractExecutorService and all call execute internally. execute is overridden/provided by the ThreadPoolExecutor directly.
The full answer is a composition of two answers that were published here (plus a bit "extra"):
By submitting a task (vs. executing it) you get back a future which can be used to get the result or cancel the action. You don't have this kind of control when you execute (because its return type id void)
execute expects a Runnable while submit can take either a Runnable or a Callable as an argument (for more info about the difference between the two - see below).
execute bubbles up any unchecked-exceptions right away (it cannot throw checked exceptions!!!), while submit binds any kind of exception to the future that returns as a result, and only when you call future.get() a the (wrapped) exception will be thrown . The Throwable that you'll get is an instance of ExecutionException and if you'll call this object's getCause() it will return the original Throwable.
A few more (related) points:
Even if the task that you want to submit does not require returning a
result, you can still use Callable<Void> (instead of using a Runnable).
Cancellation of tasks can be done using the interrupt mechanism. Here's an example of how to implement a cancellation policy
To sum up, it's a better practice to use submit with a Callable (vs. execute with a Runnable). And I'll quote from "Java concurrency in practice" By Brian Goetz:
6.3.2 Result-bearing tasks: Callable and Future
The Executor framework uses Runnable as its basic task representation. Runnable is a fairly
limiting abstraction; run cannot return a value or throw checked
exceptions, although it can have side effects such as writing to a log
file or placing a result in a shared data structure. Many tasks are
effectively deferred computations—executing a database query, fetching
a resource over the network, or computing a complicated function. For
these types of tasks, Callable is a better abstraction: it expects
that the main entry point, call, will return a value and anticipates
that it might throw an exception.7 Executors includes several utility
methods for wrapping other types of tasks, including Runnable and
java.security.PrivilegedAction, with a Callable.
From the Javadoc:
The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.
So depending on the implementation of Executor you may find that the submitting thread blocks while the task is executing.
Just adding to the accepted answer-
However, exceptions thrown from tasks make it to the uncaught
exception handler only for tasks submitted with execute(); for tasks
submitted with submit() to the executor service, any thrown exception
is considered to be part of the task’s return status.
Source

Categories

Resources