I have a Java program that I need to kill a thread.
It does not need to be killed gracefully, I just need the thread to end, as I am calling it to kill a bunch of threads as an action handler for JavaFX on window close.
Here is the program in question: https://github.com/Aashishkebab/Sorting-Simulator
Basically the program implements a bunch of sorting algorithms and allows the user to choose one, and then choose a block size.
The program splits the sorting into blocks of the size that the user inputs, and then sorts all of these concurrently on separate threads.
However, closing the window causes the threads to keep sorting in the background. I need to be able to cause all of these operations to stop on window close (or pressing a kill button or whatever the case).
I am not worried about the safety of the data, or if null pointers occur, etc. I just want the program to truly exit.
Just make the threads daemon threads. A daemon thread is one which does not prevent the JVM from exiting. This can be as simple as
Runnable mySortAlgorithm = ... ;
Thread thread = new Thread(mySortAlgorithm);
thread.setDaemon(true);
thread.start();
If you are using an executor to manage your threads, i.e. you have
Executor exec = ... ;
//...
Runnable mySortAlgorithm = ... ;
exec.execute(mySortAlgorithm);
you can create an executor that creates daemon threads, for example
Executor exec = Executors.newCachedThreadPool(runnable -> {
Thread t = new Thread(runnable);
t.setDaemon(true);
return t ;
});
//...
Runnable mySortAlgorithm = ... ;
exec.execute(mySortAlgorithm);
If you use Executors to create an ExecutorService and submit() your Callable tasks to that, all task threads can be stopped with myExecutorService.shutdownNow()
If you want even better control over your threads, look into CompletableFuture.supplyAsync()
What about System.exit(myExitCode);.
But a cleaner solution would be to make your sorting algorithm cancellable. See here for example.
Also useful is this.
It's not safe kill thread directly.
Recomended way is to use a flag that can notify to thread that is time to stop.
If you can access and modify code you can create a method named stop() in your thread class so when you need to kill process you can call myClass.stop().
For example:
public class myClass{
private boolean keepAlive = true;
public void run(){
keepAlive = true;
while(keepAlive){
//do work
}
}
public void stop(){
keepAlive = false;
}
}
Related
This question already has answers here:
How to start/stop/restart a thread in Java?
(9 answers)
Closed 9 years ago.
What are all the different possibilities to bring the dead thread back to runnable state.
If you look at the Thread Life Cycle Image, there is no way you can go back to new position once your thread has terminated.
So there is no way to bring back the dead thread to runnable state,instead you should create a new Thread instance.
From the JavaDocs...
It is never legal to start a thread more than once. In particular, a
thread may not be restarted once it has completed execution.
You'll have to start a brand new instance.
Preferably, the actions you want to execute should be wrapped up in a Runnable interface, that way you can simply pass the Runnable to a new instance of Thread
I guess you extended the Thread class and you have overridden the run method. If you do this you are tying the runnable code to the Thread's lifecycle. Since a Thread can not be restarted you have to create a new Thread everytime. A better practice is to separate the code to run in a thread from a Thread's lifecycle by using the Runnable interface.
Just extract the run method in a class that implements Runnable. Then you can easily restart it.
For example:
public class SomeRunnable implements Runnable {
public void run(){
... your code here
}
}
SomeRunnable someRunnable = new SomeRunnable();
Thread thread = new Thread(someRunnable);
thread.start();
thread.join(); // wait for run to end
// restart the runnable
thread = new Thread(someRunnable);
thread.start();
This practice makes it also easy if you need to remember the previous run state.
public class SomeRunnable implements Runnable {
private int runs = 0;
public void run(){
runs++;
System.out.println("Run " + runs + " started");
}
}
PS: Use a java.util.concurrent.Executor to execute Runnables. This will decouple thread management from execution.
Executor executor = Executors.newSingleThreadExecutor();
...
SomeRunnable someRunnable = new SomeRunnable();
executor.execute(someRunnable);
Take a look at Executor Interfaces
The thread is a separate light weight process which executes independently irrespective of other threads. Once its execution is complete, there exists no means to restart it.
The other obvious solution is: if you need the thread functionality many times, don't let the thread die. Instead of letting it exit, and so terminate itself, shove in a while(true) loop with a suitable wait at the top. You can then make it 'restart' its work by signaling it.
This is much quicker, safer and more efficient than continually creating/terminating/destroying threads.
When the execution of run() method is over, as the job it is meant is done, it is brought to dead state. It is done implicitly by JVM. In dead state, the thread object is garbage collected. It is the end of the life cycle of thread. Once a thread is removed, it cannot be restarted again (as the thread object does not exist).
Read more From Here about life cycle of Threads.
Thread has many different state through out its life.
1 Newborn State
2 Runnable State
3 Running State
4 Blocked State
5 Dead State
Thread should be in any one state of above and it can be move from one state to another by different methods and ways.
When a thread is completed executing its run() method the life cycle of that particular thread is end.
We can kill thread by invoking stop() method for that particular thread and send it to be in Dead State.
I have a requirement to run a thread in background in java and may need to pass some information to the thread before it starts doing its actual function.
How to implement this?
Secondly, is it possible to start a thread which does further operation and exit from request context. Please note that I have to implement in a web application.
An example to answer your first question:
class NewThread extends Thread
{
public String someInformation;
#Override
public void run()
{
System.out.println(someInformation);
}
}
public class YourClass
{
public void startANewThread()
{
NewThread newThread = new NewThread();
newThread.someInformation = "hello";
newThread.start();
}
}
As for your second question: This code should run in a web application, but you must be extremely careful to make sure, that these background Threads will finish at some point, or else that would be a nice little memory leak.
Please note, that if you want to share information when both Threads are running, you need to synchronize information access.
Depending on what the background Thread does it might make sense to use a framework like Quartz
is it possible to start a thread which does further operation and exit from request context. Please note that I have to implement in a web application.
You can use an ExecutorService to pass any number of tasks to and shutdown when you have finished with it.
Try this block of code, with two threads, where one thread will run in background and another thread will start executing the task. And here you can set a return type as well unlike thread.run() method.
FutureTask<Response> future = new FutureTask<>(newCallable<Response>() {
public yourreturntype call() {
doSomething(Thread1);
}
});
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(future);
doSomethingelse(Thread2)
//This thread doesnot wait for thread1 to complete
I'm trying to figure out how to multithread in java. Right now, my program works fine with no concurrency but I want to implement multithreading to help speed it along.
The program runs several objects of a separate sub class and 50% of the time evaluation for each of those objects is spent in a process which only utilizes one core rather than the 8 available. These objects are completely independent of one another until but are used as inputs in the program.
I am trying to multithread this by having the subclass implement Runnable and then have my program use a thread for each such object. Would this be the correct way?
However, how are threads in java handeled? Would I need to dispose of the threads after each run? How does join work?
thanks
Don't manage threads manually, take a look at executors and thread pools in java
You're pretty much on track. You'll create a Thread object
Runnable r = new MyClassImplementingRunnable();
Thread t = new Thread(p);
t.start();
t.join(); // wait for thread to die
The Thread object is garbage collected like any other object, the thread itself dies when the run method completes. The key thing is that your Runnable's run method really must guarantee to return, your design cannot depend on being able to kill thread from the outside.
If you are going to have lots of threads you need to wait for them all to finish, so you can either keep a collection of the threads you've started and then use t.join( smallNumberOfMillis) to see which of them has finished. That's a little inefficient so there are other techniques for allowing threads to communicate with each other, I'd suggest reading this article about them.
#denis also mentions that the Executor and related classes provides a nicer abstraction above Threads. If you have an interest in learning the background then manually managing Threads is interesting. If you just want to get the job done, follow Denis' suggestion.
Take a look at http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
The constructor takes the number of threads you want. In this case the same as your number of cores.
ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(8);
List<Future> futures = new ArrayList<Future>();
foreach(...something...)
futures.add(s.submit(new MyCallable()));
foreach(Future f : futures)
f.get(); // Result of computation
System.out.println("Done");
This is a good way to start multithreading.
public class ThreadExample {
public static void main(String[] args) {
//Main thread
System.out.println("Main thread");
new Thread(new Runnable() {
#Override
public void run() {
//This thread is independent of the main thread
System.out.println("Inner Thread");
}
}).start();
}
}
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.