This question already has answers here:
Java - Stop a thread automatically when program ends
(2 answers)
When does the main thread stop in Java?
(7 answers)
Closed 4 years ago.
Imagine you have an application A and a Thread-class like:
public class MyThread extends Thread {...}
From A, you start the thread with:
new MyThread.start();
Then when application A finishes, does MyThread also stop? Otherwise, how to ensure that it will be interrupted?
There are two ways that a thread can run in Java:
As a normal application Thread
As a "daemon" thread.
When the JVM exits, it checks to see if there are any non-daemon threads still running, and it will wait for those to exit. If you don't want the JVM to wait for those background threads, make sure to call the method setDaemon(true) on the Thread.
For more details, look at this other question:
What is a daemon thread in Java?
Also, as a side comment, the recommended way to run a thread in Java these days is to implement Runnable, not extend Thread. See more details here.
"implements Runnable" vs "extends Thread" in Java
By default, no, the JVM will continue running until your thread exits. You can use System.exit to stop the JVM entirely from any thread, or Thread.setDaemon(true) to mark your thread as a daemon which means it will not stop the JVM from exiting.
Related
This question already has answers here:
How do you kill a Thread in Java?
(17 answers)
Closed 2 years ago.
I want to create a thread to judge user codeļ¼
FutureTask<Integer> futureTask = new FutureTask(() -> run(type)); // run is a method
Thread thread = new Thread(futureTask);
thread.start();
As we all known, an infinite loop may be written in the user code, so the method run will be working all the time and the Thread thread will not stop. I want to terminate this thread after timeout duration. How can I terminate it instead of using Thread.stop because it's unsafe?
The correct way to deal with a thread that needs to be stopped is to design the thread's code so that it responds appropriately to being interrupted:
Long computations need to occasionally check the current thread's "interrupted" flag.
InterruptedException should be handled appropriately.
The thread application code's response to the interrupt should be to gracefully stop what it is doing1 and (typically) allow the thread to terminate.
(You could also use a custom flag implemented using a volatile shared variable instead of the interrupted flag. However, that doesn't deal with interrupting wait, sleep and similar operations, and is therefore a poor substitute for interrupts.)
The unsafe way is to call the deprecated Thread.stop() method. (The javadocs explain why it is unsafe, and we don't need to repeat that here.)
The (related) Thread.stop(Throwable) method was removed in Java 11; see:
Java 11 Removes stop() and destroy() Methods.
https://bugs.openjdk.java.net/browse/JDK-8204243
Unfortunately, there is nothing in between these two approaches for interrupting a thread.
If you cannot get your long running thread to cooperate, the safe alternative would be to run it in a separate process; e.g. using System.ProcessBuilder etcetera to run the java command. The (external) process could then be killed if it took too long. The downsides include:
An external process cannot access the current JVM's variables, etcetera. So you need to use a different mechanism to pass information between the parent and child processes.
Starting a new JVM is a lot more expensive than starting a new thread.
1 - For example, if the thread owns resources such as open files or sockets, it should release them. If it is performing an action for some other thread that will be waiting for the result, it should signal (in the appropriate way) that there will be no result. And so on.
Terminating thread from outside is ALWAYS unsafe and very strongly discouraged. You need to notify the thread that you want it to terminate and the thread must do it itself. That is done with method interrupt() of the class Thread. In your example it would be from the main code to call thread.interrupt() That will cause the interrupt flag to be raised in your thread. In your run method of your thread you should check for that flag (See methods interrupted() and isInterrupted() in the class Thread). Once you see that your flag is raised, break out of the loop and finish the method. That will stop your thread.
This question already has answers here:
When is a Java thread alive?
(7 answers)
Closed 2 years ago.
Is the interruption bit of a java.lang.Thread guaranteed to be set, when a thread is interrupted after it was started (Thread#start() was called) but before it begins its execution (its run method is not yet called by the JVM)?
So that within the thread Thread.interrupted() returns true or a InterruptedException is thrown when a method is called, that reacts to interruption in this way,
Or with an example:
Will the following snippet of Java code always, under any circumstances, print true?
AtomicBoolean flag = new AtomicBoolean(false);
Thread thread = new Thread(() -> {
while (!flag.get()) {}
System.out.println(Thread.interrupted());
});
thread.start();
thread.interrupt();
flag.set(true);
The java-doc of java.lang.Thread#interrupt() says:
Interrupting a thread that is not alive need not have any effect.
And the doc of java.lang.Thread#interrupted() says:
A thread interruption ignored because a thread was not alive at the
time of the interrupt will be reflected by this method returning false.
My assumption is that alive from these docs refers to the description in Thread#isAlive():
A thread is alive if it has been started and has not yet died.
From this, my answer would be yes. But I read in some sources that thread interruptions, which are done before the thread is running, are ignored. When I ran the code snippet it always printed true (but we know this isn't a guarantee in concurrent programming).
Therefore I'm searching for clarification.
It depends on scheduler when it is actually starting your thread and when finishing and you dont have control over thread scheduler. It is not gauranteed that thread is immediately started when you call thread.start(). It is possible that main thread has got chance to excute thread.interrupt(); before your thread got CPU chance.
Or with an example: Will the following snippet of Java code always, under any circumstances, print true?
If you have written this in main method then it will always print true because main is deamon thread in java and runs until its child thread gets completed. If main thread exited before thread was scheduled then nothing will be printed
This question already has answers here:
What does 'synchronized' mean?
(17 answers)
Closed 4 years ago.
A Java thread A fails to execute synchronized statement as another thread has got the monitor.
The thread A is queued by the JVM?
And how thread A is activated after, via 1) or 2) ?
As soon as the monitor is released JVM will send up this signal , thread A may be activated
the JVM will detect whether the monitor is available in a period of time, if the monitor is available, thread A may be activated
The Java Language Specification says it in section 17.1 Sysnchronization:
[...] Only one thread at a time may hold a lock on a monitor. Any
other threads attempting to lock that monitor are blocked until they
can obtain a lock on that monitor. [...]
This question already has answers here:
How Thread run starts?
(5 answers)
Closed 8 years ago.
....As the title of the questions says, I want to know what all things internally happen when we call Thread.start() and when does the start method return and main resume to execute. What all things internally get triggered like registering the thread with scheduler etc..? Also why executors are used ?
When you call t.start the JVM creates a new thread of execution (with its own stack). This is done by native code, it is not done in Java. So then the JVM itself calls t.run in the newly created thread of execution. This is usually a source of confusions (for starters) as the Java class Thread has the same name as the concept thread of execution. I guess one can think of these two as: the latter is the 'physical concept', the former is its 'abstract Java representation as a class'.
It usually takes some time between you calling t.start in the current thread of execution, and the JVM calling t.run in the newly created thread of execution; there's some time lag there as creating a new thread of execution is a somewhat heavy operation.
Thread.start
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
This question already has answers here:
Is it legal to call the start method twice on the same Thread?
(11 answers)
Closed 9 years ago.
I am making a program and I need one thread to stop and another to start. my problem is that if I do t1.stop() than t1.start() I get the java.lang.IllegalThreadStateException
if (t1.isAlive() == true){
t1.stop();
// above I stop the thread and call another
t2.start();
System.out.println("t1 was playing");
}else{
t2.stop();
t1.start();
// above I stop the other thread and want to start the first thread again, but when I run the program I get the exception i said above
}
When a thread is stopped, you cannot restart it.
However, you can create and start a new thread.
Also, you can suspend and resume the thread.
The java primitive to suspend and resume a thread (along with stop etc) is deprecated. See this to figure how you can achieve best what you need - http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Check how you can do the equivalent of suspend & resume
What should I use instead of Thread.suspend and Thread.resume?
As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.
Example code is given in the same answer to help you achieve this.
Thread#stop is deprecated and you shouldn't use it.
From the JavaDocs
stop()
Deprecated.
This method is inherently unsafe. Stopping a
thread with Thread.stop causes it to unlock all of the monitors that
it has locked (as a natural consequence of the unchecked ThreadDeath
exception propagating up the stack). If any of the objects previously
protected by these monitors were in an inconsistent state, the damaged
objects become visible to other threads, potentially resulting in
arbitrary behavior. Many uses of stop should be replaced by code that
simply modifies some variable to indicate that the target thread
should stop running. The target thread should check this variable
regularly, and return from its run method in an orderly fashion if the
variable indicates that it is to stop running. If the target thread
waits for long periods (on a condition variable, for example), the
interrupt method should be used to interrupt the wait. For more
information, see Why are Thread.stop, Thread.suspend and Thread.resume
Deprecated?.
Threads are also non-re-entrant, or, are single use. Once the run method terminates, they can not be restarted