Interrupting a runnable in executor threadpool - java

Suppose I started 10 threads using executor framework in java. I want to stop/interrupt a callables based on certain conditions later on. What is the best way to do that. I understand future.cancel(true), does not solve the issue.

Check this article.
Calling shutdownNow() or cancel() doesn’t stop the ongoing runnable. What these methods do is simply call .interrupt() on the respective thread(s). The problem is, your runnable doesn’t handle InterruptedException (and it can’t). It’s a pretty common problem described in multiple books and articles, but still it’s a bit counterintuitive.
In order to do that, you need to do quite a few things.
Extend Runnable
Make the “cancellable” resources (e.g. the input
stream) an instance field, which provide a cancel method to your
extended runnable, where you get the “cancellable” resource and
cancel it (e.g. call inputStream.close())
Implement a custom
ThreadFactory that in turn creates custom Thread instances that
override the interrupt() method and invoke the cancel() method on
your extended Runnable
Instantiate the executor with the custom
thread factory (static factory methods take it as an argument)
Handle
abrupt closing/stopping/disconnecting of your blocking resources, in the run()method

Related

Advantage of directExecutor

As far as I understand Guava's MoreExecutors.directExecutor() creates an Executor which will executes the runnable before the execute method call could return.
What are the usecases that need direct executor ? Can't the caller directly call runnable.run() directly instead of the extra level of indirection by creating an executor and submitting the runnable to this executor ? May be I am missing the real purpose of it's existence. I wanted to understand in what case is this useful.
There are few places which require both Runnable and Executor.
One of then is for example ListenableFuture and its addListener method. The only way how to execute listener immediately within the same thread is to provide direct executor.
MoreExecutors.directExecutor() is useful when you call an API that requires you to specify an executor to execute the task (e.g. Futures.transform(), listenableFuture.addListener(), etc).
Note that when you use directExecutor() with these APIs, the runnable may be run on one of these two threads:
The thread that completes the previous future
The thread that calls transform()/addListener()
This uncertainty could cause unexpected issues. So be careful when you use directExecutor().

Non-cancellable futures returned by a thread-pool. Do they exist?

I'm currently implementing a service that works in a concurrent setting and that has as operations a bunch of blocking methods.
I would like to change that so they return a Future<?> instead and it's up to the client to decide whether he wants to execute get() and block the thread or not. The problem is that Future<?> brings baggage, ie, it is possible to invoke cancellation on a future. But if that were to actually happen then it would most probably break my service's invariants.
Is there any easy way to make a thread-pool return non-cancellable futures? Currently, the only solution I'm seeing is wrapping the thread-pool future's into a future of mine that will throw an UnsupportedException if some attempts to cancel the operation. Or just return an object of my own, but I'd like to KISS if possible.
I think, you fear too much. I see two VERY simple solutions:
decorate (wrap) the default FutureTask and override in your ExecutorService the newTaskFor() method returning your new class.
do nothing, i.e do not cancel any work in your Callables or Runnables. In order to make your life easier you could take a look at Guava's uninterruptibles.

When you should implement Runnable?

I was reading some articles on topic "implement runnable vs extend thread" and I do understand that implementing runnable is prefered because in Java you can't have multiple inheritance. I also read some article that said when you use run() method it just executes the code in current thread, and when you use start() it creates new thread which is I think better, but it depends. But I am still confused about, why you should implement Runnable in class? Why is that needed? Or extending Thread? You can create anonymous thread and start it without implementing runnable or anything.
Sample code of anonymous thread without implementing or extending
new Thread() {
public void run() {
System.out.print("Example");
}
}.start();
EDIT: After some answers and comments, I think what I did not understand was bit more clarified. I actually did not know the reason of implementing Runnable if its run method does not create new Thread. But many of you told me you can use something like this
new Thread(new Runnable())
So finally I want to know - This code up here, does it create a new Thread and executes the code inside the run method ?
Runnable or Callable is the preferred idiom
Pretty much always implement Runnable or Callable you should never in normal cases need to sub-class Thread directly.
If you do need specialized behavior of the Thread class, you either know what you are doing and why you need a different behavior for the Thread class for a good reason, or you are in way over your head.
Executors are the way to go
For most cases you should be using Executors and the plumbing around them instead of rolling your own when dealing with multiple Threads and their interactions and management.
You should never create a new Thread and manage its life-cycle anymore, error prone and hard to manage, lean on the Executors and leverage them.
why you should implement Runnable in class?
The only way to implement any interface is to define a class. Here are docs on Java interfaces.
Why is that needed? Or extending Thread?
You need to do one or the other if you want to use Thread directly. As others have pointed out, you should take a look at the ExecutorService classes which provide thread-pool support and hide the Thread stuff from the user. Here's the tutorial on the subject.
You can create anonymous thread and start it without implementing runnable or anything.
Your code is an anonymous class that extends Thread. As Ishtar provides, here are the docs about anonymous classes in case there is a question. If you looked at the .class files generated by the Java compiler from your code sample you would see something like Main.class and Main$1.class. Java is actually creating a class for you on the fly.
You could also so an anonymous class which implements Runnable:
new Thread(new Runnable() {
public void run() {
System.out.print("Example");
}
}).start();
But whether or not your use an anonymous class is orthogonal to the question of whether implementing Runnable or extending Thread is the better mechanism to define your thread task. For that question, as #MiserableVariable points out, Jon Skeet's answer is still very relevant.
When you deal with your own class hierarchy, you don't want to start from the Thread class in the first place. Thread class is an infrastructure for running your Runnables. And there is more, e.g. Executor, etc. Thread holds its state specific to its API. Runnable is a convenient (and a proper) way of wrapping your processing logic and isolate it from the surrounding it should be executed in.
It depends on your requirements, but in general it is a good idea to seperate What should be done? from Who does it?.
A Thread can execute code, but it has a lifecycle and once it finished you can't start the same Thread instance again.
A Runnable is just some code that can be executed or run(). The lifecycle of the object that implements Runnable is not necessarily bound to a thread's lifecycle and this gives you great benefit:
The same Runnable instance can be run multiple times. If you want to re-run a Runnable just create a Thread, pass the Runnable into the thread's constructor and call start().
Since a Runnable instance can be re-run easily the instance can remember the previous run's state.
The same Runnable instance can be run by multiple threads in parallel.
When you call run() method, it is method invocation on same thread rather than new thread. If you want something happen on separate thread, you either need to extend Thread (or) implement Runnable and call start() on thread object. Java thread life cycle may give you some clarity on difference between calling run() and start()
Quoting from the Oracle documentation on Concurrency.
The first idiom, which employs a Runnable object, is more general,
because the Runnable object can subclass a class other than Thread.
The second idiom is easier to use in simple applications, but is
limited by the fact that your task class must be a descendant of
Thread. This lesson focuses on the first approach, which separates the
Runnable task from the Thread object that executes the task. Not only
is this approach more flexible, but it is applicable to the high-level
thread management APIs covered later.
Note that the first idiom is Runnable and the second is extending from Thread. It looks like flexibility is the main motivator to go for implementing Runnable approach over extending Thread. I highly doubt if they both map to different implementations by the JVM (although I can't confirm it).
Anonymous classes are useful, but not applicable in most scenarios. This is as true for a Thread class, as for any other type of class.
In cases, for instance, that multiple instantiations of a Thread object are needed and that Thread object also has state (e.g., some calculation results), or communicates with other objects (e.g., via a queue), one has to extend the Thread class, or implementing the Runnable interface and then using a Thread constructor to actually start the thread.
The subject has been discussed extensively, so you can check the answers (and the links) posted to an earlier StackOverflow question, or many other similar ones.

Proper way to set timeout on a method in Java

I've looked over some existing answers here on SO and I've used Future in combination with ExecutorService to set timeout with TimeUnit to method.
But I'm trying to set timeout on a method inside my service implementation meaning that caller class is consuming interface.
So I'd like to avoid implementing callable in my service implementation, because I want this method to get executed in the same Thread.
Is there other way to set timeout or simulate timeout on a given method ?
You can have a look at TimeLimiter from guava that can take any class and produce time-limited proxy. But it still uses thread pool internally to wait for Future (at least the default SimpleTimeLimiter implementation).
I you want to run method in the same thread, you must have another thread to interrupt it after given timeout. And interruption won't always work. Thus thread pool and Future is the only way.

difference between thread.start() and executor.submit(thread)

i am facing a problem regarding the thread. I am having a class which implements runnable, and i can use thread.start() method on that class.
My question is i have one more class java.util.concurrent.ExecutorService in which i can call executor.submit(thread)..
can anyone please tell me what is the difference between thread.start() and executor.submit(thread)...
The executor.submit method takes a Runnable, not a Thread. The point of executorServices is that they take control over creating and pooling threads so the code calling them doesn't have to.
You should not submit a thread to an executor. First it is simply a waste because the only method that will be called on it is run(), and you just need a Runnable and don't need a Thread for that.
Secondary, while this issue is solved in the latest JDK, it used to be the case that a memory leak problem occurs if you create a lot of Thread objects and don't call .start() on them. Basically creating a Thread objects allocates some memory that can only be reclaimed after .start() was called. Therefore, doing executor.submit(thread) is potentially hazardous in earlier JDKs (I think it was only solved in JDK6 or so).
Coming back to your question, executor.submit(thread) is not valid.. It is simply wrong, because an executor uses its own thread to execute the runnable. That's after all the whole point of using a executor. You want to separate task (invocation) and execution. Only if you want to supply the executor (thread), you should be using Thread, but it is rare that you need to do so. Generally it is advisable to implement a Runnable and use executors to execute it, rather than dealing with Thread yourself.

Categories

Resources