This question already has answers here:
Is there a good way to forcefully stop a Java thread?
(7 answers)
Closed 2 years ago.
Is there a way to stop, kill or destroy a kid thread by the main thread who started it?
Everyone suggest to use some variable to check inside the thead itself, for exit when variable change state.
I can't do that, the thread is a very complex and big program and is not possible to foresee every conditions that could make it running in loop.
I need to force kill the thread from extern when time exceeded.
Thanks
No,
There is no safe way for one thread to forcibly kill another. There is no safe way for one thread to force another thread to do anything.
The problem is, threads communicate through shared variables. And, the author of any multi-threaded program must carefully "synchronize" the activities of the different threads, so that no thread can ever see the shared variables in some invalid state that was caused by the activity of another thread.
If you make it possible for a thread to be killed at any time, then there is no way you can ensure that the killed thread won't leave shared variables in an irreparably bad state.
If you can't work around the need to kill a "child," then you should re-write the code so that the child is a child process. Processes only share state in much more controlled ways, and it is much easier to write an application that can safely continue to execute after killing off a rogue child process.
Related
This question already has answers here:
What is thread Safe in java? [duplicate]
(2 answers)
Closed 2 years ago.
I have a program where I want my threads to make a sort of update to something else, but since I start all of the threads at the same time, they make the update at the same time which defeats the purpose because they all overwrite each other. I want a thread to update something, have that something use it quickly, then get changed afterwards. Is there a way to allow any thread to go first and then have the others wait? It feels like I can't do anything because if I change the thread class, then all of the threads will perform the change and still execute at the same time. I am using a GUI too, so I can't just use Thread.Sleep between each thread's start call. I don't think any code would help the question, I just want to know if there's a way to block all threads but one, or delay each thread from getting to the same line of code at the same time, since they all change a variable.
Use a synchronized block for this purpose. When a block of code is wrapped in synchronized, only a single thread can access it, and other threads wait for their turns
synchronized(this)
{
// your line of code
}
This question already exists:
In Java, how do I test if an object's monitor is locked? [duplicate]
Closed 5 years ago.
In Java, how do I test if an object's monitor is locked? In other words, given a object obj, does any thread own obj's monitor?
I do not care which thread owns the monitor. All I need to test is if ANY thread owns a given object's monitor. Since a thread other than the current thread could own the monitor, Thread.holdsLock( obj ) is not enough as it only checks the current thread.
I am trying to figure the simplest solution possible.
This is not a duplicate because:
I cannot use higher-level/newer concurrency/locking mechanisms. I cannot use Lock, etc. I must use low-level/old/traditional currency/locking mechanisms such as synchronized, wait(), etc.
I am not trying to find a time to execute code when has monitor has become unlocked. I am trying to execute code when a monitor is locked.
In fact, to give a little bit of background, this part of a unit test where I am trying to start run two threads which both need to lock the same object.
I cannot call internal private JVM dependent methods such as sun.* .
As a result, in order to test for correct handling of concurrency. I need to
Create the two threads.
Start thread 1 .
As soon as thread 1 owns the monitor, suspend thread 1 .
Start thread 2 .
As soon as thread 2 is blocked by thread 1, suspend thread 2 .
Resume thread 1 .
Join thread 1 .
Run some assertions.
Resume thread 2 .
Join thread 2 .
Run some assertions.
What I am trying to figure out is the best way to do #3, primarily, determining when thread 1 owns the monitor.
If you really want to do this using thread suspension, you can have thread 1 set a thread safe flag when it has the monitor and observe the flag from your test thread.
However, I doubt that's the best way to put together your test. If you just want to test the business logic in your threads, you can run thread 1, join it, run your first set of assertions, then run thread 2, join it, and run your second set of assertions. Better yet, you could put the business logic in Runnables and test them in your test thread by invoking the run() method directly.
If there's an issue with thread synchronization that you are trying to get at, my experience is that using time delays is a better way to test those issues than interacting directly with the threads, as interacting directly with the threads may introduce or hide synchronization issues. For more on that, see my answer on the general question of testing threaded code here:
How should I unit test threaded code?
Your original question was how to check if any thread owns a lock. The ThreadMxBean should help you out. You can obtain an instance by calling
ManagementFactory.getThreadMXBean()
You should first check if you platform supports monitoring of object monitor usage by calling isObjectMonitorUsageSupported. If that is the case you can get information about all threads including lock info by calling
ManagementFactory.getThreadMXBean().dumpAllThreads(true,true)
This returns an array of ThreadInfo objects on which you can call the getLockedMonitors method which will give you hints on the locked objects, namely the result of calling System.identityHashCode on that object which should uniquely identify that object. Pretty clunky alltogether but at least a way to go.
Apart from the virtual answer to your question I don't think your approach is a sensible one. Your original goal is still not clear to me why I can't give you conrete advise. Maybe you should investigate best practices on testing multithreading?
This question already has answers here:
How to stop uninterruptible threads in Java
(6 answers)
Closed 9 years ago.
It is a widely known fact that one shall not stop running processes using Thread.stop().
Usually the manuals and tutorials suggest using Thread.interrupt() or some boolean variable instead, and checking from inside the code for that interrupt or variable.
But if I have a library method which takes a very long time to execute sometimes, and I want to give user an ability to stop that process? And library does not give me a mechanisms to do it (does not check thread interrupted status, and no "stop!" variables)?
And, to add to the bad things, there is either no source code for library, or it is just too big to edit it and add checks at appropriate places.
It seems that Thread.stop() is the only solution here. Or maybe there is some workaround?
Why you do not try to use sleep(long timeout) when are waiting for some condition and if had not success, you simple "return" from the thread?
Probably your thread is running in a while (booleanVariable) { },
if it is, you could set this variable as volatile, and the thread controller set it as false.
Think of the Thread.stop() like the System.exit(value), it works, but when you have some bug making you thread stop/vm exit, will be much more harder to find it out.
If practical in your situation, spawn another process and treat that as the unit of work, rather than a thread. Process killing is much more deterministic, though devoting a process to what used to be a thread's work might be too heavyweight for your situation.
The only solution better than using Thread.stop() is to use the library in a seperate thread which you can kill to stop it.
You may want to look for different handles of the function you are running, for example if its IO you can try to close any open connections/streams. If you are stuck with this library (IE can't find one that has better interruption mechanics) Thread.stop() is your only way of stopping the thread.
Thread.stop() is deprecated from java 4 onwards..I read an article to stop a thread by wrapping the call to the library in an separate class that implements InterruptibleChannel which is part of java.nio.
Interruptibleclasses has close() method, through which another thread can call it asynchronously.
Up to now I used my application as a stand alone product. So, when user pressed "Stop" button I called System.exit(0); and it was fine.
Now my application will be called (in a programmatic way) from another program. So, I afraid that System.exit(0); will kill not only my process but also the external software which started my program.
So, what is the correct way to shutdown my application if a corresponding request from an external software is received? My application is an GUI application. So, I want to close the window but I also want to close all processes performed by my program.
ADDED:
To be more specific, I want to close all threads started by my program. My program does not start any OS process or any other program.
If the threads you've launched are still processing then calling System.exit(0) will cause them to be killed. In some cases, this can leave your application in an inconsistent state. Imagine that the thread was saving a file for example.
You should ensure that the your threads are all 'happy' to die before calling System.exit.
One technique you can use for this with long running threads is poisoning. To do this you send the threads a message that they should now die gracefully - i.e. a poson message. Once they have all died, it is safe to call System.exit(0) to terminate the Swing event handling thread.
There a loads of different ways of implementing poisoning, you could just set a global flag variable that the threads check to see if they've been poisoned, or you could use the Java 5 threading libraries. Take a look at this Javadoc for example and you'll find references to this technique:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html
As long as your programm isn't sharing an application server with others, shuting down the VM by calling System.exit(0) terminates all threads.
From Javadoc
System.exit Terminates the currently running Java Virtual Machine)
EDIT:
If you want to do some clean up code before shutdown, http://java.sun.com/j2se/1.4.2/docs/guide/lang/hook-design.html
There is on "one-size-fits-all" answer to this that's a drop-in replacement for System.exit, unfortunately.
You will generally need to set some kind of flag that signals to all of your threads that it is time to exit, and ensure that they check this flag regularly. This will let them clean up gracefully without stopping abruptly, and it also ensures the effects are limited to your own components. In this case your application's main thread would also observe the flag, wait for all the "worker" type threads to finish and would then return all the way up the stack until your application's entry point was reached.
This question is not too dissimilar to the deprecated Thread.stop (etc) methods, especially with regards to replacing System.exit with something more respectful. In that light, the why is Thread.stop() deprecated page may be useful reading.
Throwing an exception (a custom one called something like ApplicationStopException) to unwind the stack of the main thread is not such a bad idea; this prevents you from having to handle the special logic all over your code and instead lets the "message" propagate to the higher levels, where they can take whatever action is needed to exit your program gracefully.
I recommend you to do flagging to stop the thread so that the thread will know when it has to stop. For GUI and window, you can call frame.dispose().
For System.exit(), I think it will not affect the caller, you may try to see what is the real effect but as other people already recommended, do not call it directly like that, just let the threads stop by itself
This question already has answers here:
How to abort a thread in a fast and clean way in java?
(15 answers)
Closed 2 years ago.
I'm in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of "stuff".
There are certain instances where the connection fails and I need to stop everything and start from scratch with a new object.
I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.
What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else?
Assuming your threads are reasonably under your control - i.e. they're not calling anything which is going to potentially wait forever without your code executing - I would shut it down with a simple (but thread-safe - use volatile!) flag.
See this article for an example in C# - the Java equivalent should be easy to work out. Calling interrupt won't have any effect until the thread next waits, and stop can leave your app in a hard-to-predict state. Wherever possible, go for a clean, orderly shutdown instead.
Use your_thread.interrupt and check in your thread if Thread.interrupted() return true. If so, close your thread properly.
private Thread m_CleanupThread = null;
public void threadCleanUp(){
m_CleanupThread = new Thread(this);
m_CleanupThread.Start();
}
This thread will terminate and garbage collector will do the rest.