I found this solution to know if a thread has been interrupted.
public class OurThread extends Thread(){
private volatile boolean stop = false;
public void run(){
while (!stop) {
//Do your actions
}
}
}
But my run method is only executed once, so It doesnt make sense to put it insisde a while loop. Another approach I found, is to check the Thread.isInterrupted() flag, and then terminate the thread. My run() method is pretty long so I would have to check lots of times this condition making my code dirty.
I have to apply this into four diferents processes so im trying to find a simpler, cleaner soution. I was hoping if is there something like:
try{//my code}
catch(interrumption)
The problem is that since my thread is interrumped by using future.cancel(), the interruption is not thrown inside my run() code, then i cant do that either.
Any suggestion?
By now im checking lots of times between the code if the thread has been cancelled.
Thanks :)
Firstly, don't extend Thread, you should implement Runnable or Callable.
Secondly you can add a method like
static void checkInterrupt() {
if(Thread.currentThread().isInterrupted())
throw new IllegalStateException("Interrupted");
}
and place this in the four places. This doesn't add much code and isn't as ugly as a task which won't stop.
Your task ( Runnable or Callable) can't be interrupted unless it has inbuilt mechanism to respond to interrupts. Also it depends on your design; like, when exactly task expects to be interrupted. Usually we do when the task has reached a safe state.
So you check if interrupt is received and then respond appropriately. To reuse code you can use approach suggested by #Peter.
Related
I'm writing an android application.
In the main thread, it is possible to define methods and then call the methods, which helps keep the code clean. In a new thread, how does one define methods, to avoid writing all the code in "one block"? Is it possible to call methods defined in the main thread, or can you define them inside the new thread somehow?
So to be clear, what I want to do is this:
volatile Runnable feedToBuffer = new Runnable()
{
#Override
public synchronized void run()
{
if(boolean)
{
MethodA();
}
else
{
MethodB();
}
}
and not this:
volatile Runnable feedToBuffer = new Runnable()
{
#Override
public synchronized void run()
{
if(boolean)
{
//Code that was in MethodA
}
else
{
//Code that was in MethodB
}
}
}
Is that possible?
I realize this info is probably out there somewhere, but haven't found it, so really grateful for any help. :)
It's perfectly possible. Thread is just a sequence of actions, and if it involves a method call, it will be executed within that sequence. It doesn't matter.
Threads are in no way tied to the structure of your code. The main difference between the threads you start and the one you have already when the app starts is the points of entry. When Android starts the main thread, it enters your app in many points, in the activity that would be the lifecycle calls like onCreate() or button click listeners. When you create a new thread, your point of entry is the run method from where you can call anything you want.
There is also a difference in that the main thread runs an event loop. Basically, there is a queue of messages that it has to process. Each time something arrives to the queue, it processes the message, then goes back to waiting. In that sense the main thread never ends. Your thread, however, stops when it reaches the end of the run method. Of course, you can implement a similar event loop for your thread yourself.
Other than that there are no fundamental differences in how the threads operate, you can call methods from any thread freely. Of course, there are rules of multithreading like avoiding blocking the main thread, synchronization, and so on, but it's too much to cover in one answer.
I am trying to figure out the solution for a scenario of cancelling a group of threads if one of the Thread finishes the task successfully.
The scenario is like this: Lets say a group of threads are working on a task to find a String in a file and if any of the thread finds the String, the remaining treads should stop execution.
Using 1.5 concurrency we can achieve this, but prior to JDK 1.5 if we want to achieve this kind of scenario, then how can we do that?
For Java 2 Platform, Standard Edition 1.4 SDK or higher you could use exception chaining.
How about just splitting up the thread's task into smaller chunks and checking for a stop condition in the loop?
You could interrupt the threads and in each thread check for the interrupted flag:
public class Job implements Runnable {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// perform stuff
}
}
}
In the shutdown-code you call
thread.interrupt();
for each other thread.
The advantage compared to a stop-flag is that your threads will also drop out of any blocking calls.
The good way to stop a thread is to have it periodically check a flag that indicates whether or not it should continue. The java Thread class already has such a facility, called interrupts, that is useful in many scenarios, as bennihepp points out in his answer. See the javadoc for the Thread class and the interrupt() and isInterrupted() methods in particular.
In the following example the runnable class makes sure that all of the instances halt (soon) after one instance finishes. It is worth noting that you should keep your unit of work (one iteration of the loop) small enough.
public class MyRunnable implements Runnable {
private static boolean shouldStop = false;
public void run() {
// allocate required resources
while (!MyRunnable.shouldStop) {
// do work
if (/* some condition to indicate completion */)
MyRunnable.shouldStop = true;
}
// release any allocated resources
}
}
This simple example assumes all threads wrap the same type of a runnable object. Once one sets the shouldStop flag, all others also stop. It would be quite trivial to extend the example to also facilitate interruptions.
I am storing a bunch of threads objects in an arraylist. I want to be able to start these threads at random. Same thread can be started more than once. Before I start a thread object, I check on whether the thread is alive, and if they have either of NEW or TERMINATED status. This restriction because, I don't want to disturb the 'busy' threads. Now, for NEW threads, this works fine. But for TERMINATED thread, I get an exception.
When a thread ends, shouldn't it go back to being 'new'? Or are threads 'disposable' - like use once and done?
As it says in the documentation for Thread.start(), "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."
It is better for you to keep hold of Runnable instances and implement your own logic for keeping track of when the execution of each one of them finishes. Using an Executor is probably the simplest way to run the Runnables.
You should probably be using the awesome stuff provided in java.util.concurrent. Based on your description, ThreadPoolExecutor sounds like a good thing to check out.
This is the way I did it
class GarbageDisposalThread extends Thread {
public void start() {
try {
super.start();
} catch( IllegalThreadStateException e ) {
this.arrayList.remove(this);
this.arrayList.add( new GarbageDisposalThread( this.arrayList ));
}
}
private GarbageDisposalThread() {
}
public GarbageDisposalThread( ArrayList<Whatever> arrayList ) {
this.arrayList = arrayList;
this.start();
}
public void run() {
// whatever the code
}
private ArrayList<Whatever> arrayList = null;
}
that's it!
you can change the code according to your needs :P
Java threads cannot be restarted.
From the javadoc:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
See the Thread.start() javadoc for more information.
There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.
From another post...
You could use ThreadPoolExecutor, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
So, you don't restart a thread, but you would redo/resume a task.
I have question about the Java threads. Here is my scenario:
I have a thread calling a method that could take while. The thread keeps itself on that method until I get the result. If I send another request to that method in the same way, now there are two threads running (provided the first did not return the result yet). But I want to give the priority to the last thread and don't want to get the results from the previously started threads. So how could I get rid of earlier threads when I do not have a stop method?
The standard design pattern is to use a local variable in the thread that can be set to stop it:
public class MyThread extends Thread {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
// do your things
}
}
}
This way you can greacefully terminate the thread, i.e. without throwing an InterruptedException.
The best way really depends on what that method does. If it waits on something, chances are an interrupt will result in an InterruptedException which you handle and cleanly exit. If it's doing something busy, it won't:
class Scratchpad {
public static void main(String[] a) {
Thread t = new Thread(new Runnable() {
public void run() {doWork();}
});
t.start();
try {
Thread.sleep(50);
} catch (InterruptedException ie) {}
t.interrupt();
}
private static void doWork() {
for ( long i = 1; i != 0; i *=5 );
}
}
In the case above, the only viable solution really is a flag variable to break out of the loop early on a cancel, ala #inflagranti.
Another option for event-driven architectures is the poison-pill: if your method is waiting on a blocking queue for a new item, then you can have a global constant item called the "poison-pill" that when consumed (dequeued) you kill the thread:
try {
while(true) {
SomeType next = queue.take();
if ( next == POISON_PILL ) {
return;
}
consume(next);
}
} catch //...
EDIT:
It looks like what you really want is an executor service. When you submit a job to an executor service, you get back a Future which you can use to track results and cancel the job.
You can interrupt a Thread, its execution chain will throw an InterruptedException most of the time (see special cases in the documentation).
If you just want to slow down the other thread and not have it exit, you can take some other approach...
For one thing, just like exiting you can have a de-prioritize variable that, when set, puts your thread to sleep for 100ms on each iteration. This would effectively stop it while your other thread searched, then when you re-prioritize it it would go back to full speed.
However, this is a little sloppy. Since you only ever want one thing running but you want to have it remember to process others when the priority one is done, you may want to place your processing into a class with a .process() method that is called repeatedly. When you wish to suspend processing of that request you simply stop calling .process on that object for a while.
In this way you can implement a stack of such objects and your thread would just execute stack.peek().process(); every iteration, so pushing a new, more important task onto the stack would automatically stop any previous task from operating.
This leads to much more flexible scheduling--for instance you could have process() return false if there is nothing for it to do at which point your scheduler might go to the next item on the stack and try its' process() method, giving you some serious multi-tasking ability in a single thread without overtaxing your resources (network, I'm guessing)
There is a setPriority(int) method for Thread. You can set the first thread its priority like this:
Thread t = new Thread(yourRunnable);
t.start();
t.setPriority(Thread.MIN_PRIORITY); // The range goes from 1 to 10, I think
But this won't kill your thread. If you have only two threads using your runnable, then this is a good solution. But if you create threads in a loop and you always sets the priority of the last thread to minimum, you will get a lot of threads.
If this is what is application is going to do, take a look at a ThreadPool. This isn't an existing class in the Java API. You will have create one by yourself.
A ThreadPool is another Thread that manages all your other Threads the way you want. You can set a maximum number of running Threads. And in that ThreadPool, you can implement a system that manages the Thread priority automatically. Eg: You can make that older threads gain more priority, so you can properly end them.
So, if you know how to work with a ThreadPool, it can be very interesting.
According to java.lang.Thread API, you should use interrupt() method and check for isInterrupted() flag while you're doing some time-consuming cancelable operation. This approach allows to deal with different kind of "waiting situations":
1. wait(), join() and sleep() methods will throw InterruptedExcetion after you invoke interrupt() method
2. If thread blocked by java.nio.channels.Selector it will finish selector operation
3. If you're waiting for I/O thread will receive ClosedByInterruptException, but in this case your I/O facility must implement InterruptibleChannel interface.
If it's not possible to interrupt this action in a generic way, you could simply abandon previous thread and get results from a new one. You could do it by means of java.util.concurrent.Future and java.util.concurrent.ExecutorService.
Cosider following code snippet:
public class RequestService<Result> {
private ExecutorService executor = Executors.newFixedThreadPool(3);
private Future<Result> result;
public Future<Result> doRequest(){
if(result !=null){
result.cancel(true);
}
result = executor.submit(new Callable<Result>() {
public Result call() throws Exception {
// do your long-running service call here
}
});
return result;
}
}
Future object here represents a results of service call. If you invoke doRequest method one more time, it attempts to cancel previous task and then try to submit new request. As far as thread pool contain more than one thread, you won't have to wait until previous request is cancelled. New request is submitted immediately and method returns you a new result of request.
Say I've got something like this
public void run(){
Thread behaviourThread = new Thread(abstractBehaviours[i]);
behaviourThread.start();
}
And I want to wait until abstractBehaviours[i] run method has either finished or run for 5000 milliseconds. How do I do that? behaviourThread.join(5000) doesn't seem to do that afaik (something is wrong with my code and I've put it down to that).
All the abstract abstractBehaviour class is of course Runnable. I don't want to implement it inside each run method as that seems ugly and there are many different behaviours, I'd much rather have it in the calling/executing thread and do it just once.
Solutions? First time doing something as threaded as this. Thanks!
edit: So the interrupting solution would be ideal (requiring minimal changes to AbstractBehaviour implementations). BUT I need the thread to stop if it has finished OR 5000 milliseconds have passed so something like the following would not work because the thread may finish before the while loop in the parent thread has. Make sense? Any ways around this, I'd love to do it from within the thread that starts the threads obviously.
long startTime = System.currentTimeMillis();
behaviourThread.start();
while(!System.currentTimeMilis - startTime < 5000);
behaviourThread.interrupt();
try {
behaviourThread.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
edit: nevermind I see there is a Thread.isAlive() method, all solved I think
The best way to do this is to use the thread interrupt mechanism. The worker thread / Runnable needs to periodically call Thread.interrupted() to see if it is time to stop. The second part of the equation is that a separate thread needs to call Thread.interrupt() on the worker thread after 5000 milliseconds have elapsed.
The advantages of using thread interrupts (over a bespoke solution using flags) include:
The interrupted() state is always available for the current thread. You don't need to pass around an object handle or use a singleton.
An interrupt will unblock some blocking IO and synchronization requests. A bespoke solution cannot do this.
Third-party Java applications and libraries may respect Thread.interrupt().
EDIT - as a commenter points out, you can test whether the current thread has been interrupted using either Thread.interrupted() or Thread.currentThread().isInterrupted(). The main difference between the two approaches is that the former clears the interrupted flag, but the latter doesn't.
You cannot do this externally from the run method - the run method must check some variable to see if it should exit. For example:
class InterruptableRunnable implements Runnable
{
private volatile boolean stop;
public setStop() {
stop = true;
}
public void run() {
while (!stop)
{
//do some work and occassionaly fall through to check that stop is still true
}
}
}
The key thing is for the code in the run loop to check the stop flag occasionally. You can then wire up a timer to set stop to true after 5000 milliseconds.
Finally, it's best practice not to use Threads directly, use the excellent Concurrency Framework. The Concurrency Tutorial is a good place to start and the book Java Concurrency in practice is excellent.
You may do it using java.util.concurrent package.
ExecutorService service = Executors.newCachedThreadPool();
Future future = service.submit(behaviourThread);
long startTime = System.currentTimeMillis();
while (!future.isDone()) {
if (System.currentTimeMillis() - startTime > 5000) {
future.cancel(true);
break;
}
}
// TODO: more work here
//don't forget to shutDown your ThreadPool
service.shutDown();
This code will stop your thread after 5 seconds if it has not finished it's job by that time. If you check behaviourThread.isAlive() it's gonna show false.
You do that by implementing a Runnable
public void run()
{
long time = System.nanoTime(),
end = time + 5 000 000 000; // just better formatting
do {
...my code
} while (System.nanoTime() < end && myOwnCondition);
}
Interrupt is not such a good solution, because you need to access the thread from outside
and it disturbs the program flow. The thread can terminate anytime in your code which
makes cleanup difficult. Please form a habit of letting threads run to the end because otherwise it opens nasty and difficult bugs.
If your program is so heavy duty that you don't know that the while end is reached until the task has completed I suggest the use of a labeled break:
do {
breakout:
{
..my code
if (timetest)
break breakout;
}
// cleanup
...
} while (...);