According to java when setDaemon is set to true
it does not prevent the JVM from
exiting when the program finishes but
the thread is still running. An
example for a daemon thread is the
garbage collection.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true, actually it should keep on running . when setDaemon is set false the child thread print value of i even though main thread exited.
kindly clarify my doubt.
public class DeamonSample implements Runnable
{
public void run()
{
try
{
System.out.println("T1 started...");
for (int i=0;i<1000;i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.print(i+" ");
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
System.out.println("T1 ended...");
}
}
/**
* #param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Main Started...");
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
DeamonSample deamonSample=new DeamonSample();
Thread t1=new Thread(deamonSample);
t1.setDaemon(true);
t1.start();
System.out.println("T1 Type="+t1.isDaemon());
System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
System.out.println("Main ended...");
}
}
By default threads are not daemon threads. If you get to the end of your main with any thread that's not a daemon then the process will keep running. By calling setDaemon(true) you're telling the JVM that your thread shouldn't block shutdown at the end of main.
The DeamonSample instance is assuredly not stopped when t1.setDaemon(true); is executed; the nondeterminism that you see comes from the prints. Characters are written to thread-local buffers before they are merged into a single stream.
Here's a bit of code to illustrate. Two threads take turns incrementing a counter and printing its state, but the numbers you see may be very much out of order.
import java.util.concurrent.atomic.AtomicInteger;
public class FunnyPrinter extends Thread {
static AtomicInteger counter = new AtomicInteger(0);
int parity;
public FunnyPrinter(int parity) {
super();
this.parity = parity;
}
public void run() {
for (;;)
if (counter.intValue() % 2 == parity)
System.out.println(counter.incrementAndGet());
}
public static void main(String[] args) {
FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
t1.start(); t2.start();
}
}
If you need determinism, synchronize on System.out and flush it before the end of the block.
From the following code sample , the thread created by main thread stops executing when setDaemon is set to true
This will not happen. Check your output again. Your output will contain the following lines:
Main Started...
Main Thread Type=false
T1 Type=true
Main Thread Type=false
Main ended...
..actually it should keep on running .
Being a daemon thread, it wont. Since all non-daemon threads (main) have finished, the jvm will exit.
when setDaemon is set false the child thread print value of i even though main thread exited. kindly clarify my doubt.
Correct
The main-thread terminates, before your daemon-thread can print out all your numbers...
if your new thread isDaemon = true, try this line after starting the thread ():
...
Thread t1=new Thread(deamonSample);
try{
t1.join();
}catch(InterruptedException ie){
ie.printStackTrace();
}
...
you will see, the daemon-thread will come to an end... (at least, that wouldn´t be multithreading anymore, but that example is for clarifying purpose only)
Related
I wrote this program to simulate field visibility.
package com.example.threads.fieldvisibility.main;
public class ThreadVisibilityWithSyncKeyWord implements Runnable {
private boolean stop = false;
#Override
public void run() {
while (!stop) {
// System.out.println("stop is " + stop);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadVisibilityWithSyncKeyWord test = new ThreadVisibilityWithSyncKeyWord();
Thread t = new Thread(test);
System.out.println("Starting Thread");
t.start();
Thread.sleep(5000);
System.out.println("Stopping Thread");
synchronized (test) {
test.stop = true;
}
t.join(5000);
System.out.println("Thread State: " + t.getState());
}
}
The program is pretty straightforward. we have two threads. Main thread does change flag "stop" to true in a synchronized block using "test" object.
I expected once this is set to true by main thread, it would make while loop to terminate. But even though main thread made flag to true , the other thread doesn't see the latest value (even though it was updated in a synchronized block).
Strangely, when I uncomment System.out.println() (inside while) the thread does "see" the latest value and terminates.
I didn't understand this behaviour. Why the other thread isn't able to see the latest values which is update in a synchronized block of main thread. And after uncommenting sysout, what causes the other thread to see the latest value of the flag?
When a thread enters a synchronized block, it is guaranteed to see the current state of the accessed variables by reading from shared cache/memory. Writing variables inside a synchronized block will guarantee that the variable is written to shared cache/memory.
Whats happening:
test is created
main-thread caches test.stop
test caches stop that is false
test starts
test reads the value stop from it's local cache (!)
main-thread sets test.stop to true
because this is done synchronized, the write is done to shared cache as well
test keeps reading stop from it's own cache, which is still false
When you add the printing line to the code, you have to know that System.out.println involves synchronization internally:
...
main-thread sets test.stop to true
because this is done synchronized, the write is done to shared cache as well
test does the println and in that moment the internal synchronization causes test to read the new value from the shared cache
I think the main issue is how the project structured if you separate the main thread class from you runnable everything would be easier.
This is working example with following results: (Note I added 1 second sleep to the thread to avoid many printouts)
Starting Thread
stop is false
stop is false
stop is false
stop is false
Stopping Thread
stop is true
Thread State: TERMINATED
package com.project;
public class Main {
public static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
ThreadVisibilityWithSyncKeyWord test = new ThreadVisibilityWithSyncKeyWord();
Thread t = new Thread(test);
System.out.println("Starting Thread");
t.start();
Thread.sleep(5000);
System.out.println("Stopping Thread");
stop = true;
t.join(5000);
System.out.println("Thread State: " + t.getState());
}
}
package com.project;
public class ThreadVisibilityWithSyncKeyWord implements Runnable {
#Override
public void run() {
while (!Main.stop) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("stop is " + Main.stop);
}
}
}
in my Java program main thread does not get interrupted. Why?
/*
* This class counts till infinity
*/
class infinityT extends Thread{
int counter = 0;
public void run(){
try{
while(true){
if(counter>500){
// this class will throw compilation error here as Thread.sleep is not a valid method here as it does not extend Thread class
Thread.sleep(1000);
}
System.out.println(counter++);
}
}catch(InterruptedException e){
System.out.println("infinity Interrupted: "+counter);
}
}
}
class interruption{
public static void main(String args[]){
Thread t = new Thread(new infinityT());
// start the thread
t.start();
try{
// main thread does not seem to interrupt
Thread.currentThread().interrupt();
Thread.sleep(2000);
}catch(InterruptedException e){
System.out.println("Main thread interrupted!");
}
t.interrupt();
}
}
Output:
...
...
499
500
infinity Interrupted: 501
Your main thread does get interrupted but what it doesn't do is sleep when you call Thread.sleep() because you've already set its interrupted flag. Hence, all or most of the numbers would get printed after the Main thread interrupted! message.
If you scroll up the console (you may have to increase its buffer or just reduce the loop count to 10 or something) you should see it getting printed as well.
As an aside, you do not need to extend Thread to call sleep() as it's a static method. Or, you can simply start infinityT directly instead of passing it as Runnable again.
main thread gets interrupted, you might have missed it among the other outputs. check carefully and if u execute the same program multiple times, see the position in which the Main thread gets interrupted
I need to kill a thread that is not created in my code. In other words, the thread object is created by api (Eclipse JFace). Here is my code
ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
try {
IRunnableWithProgress rp = new IRunnableWithProgress(){
#Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
Thread.sleep(3000);
Thread t = Thread.currentThread();
t.getThreadGroup().list();
t.interrupt();
}
};
dialog.run(true, true, rp);
}
catch (Exception e) {
e.printStackTrace();
}
Thread.currentThread() returns a thread with the name "ModalContext". Line t.getThreadGroup().list() returns the following data:
...
Thread[qtp1821431-38,5,main]
Thread[qtp1821431-39,5,main]
Thread[qtp1821431-40,5,main]
Thread[qtp1821431-42 Acceptor0 SelectChannelConnector#0.0.0.0:18080,5,main]
Thread[DestroyJavaVM,5,main]
Thread[ModalContext,5,main]
Variables "dialog" and "rp" do not have reference to their runnable object. And they don't have any method to close or cancel. So I want to kill that thread "ModalContext" directly. Calling t.interrupt() does not work. Thread MoadlContext continues to run. How can I kill the thread? Thanks
The interrupt method doesn't kill the thread. It sets the "interrupted" status on the Thread, and if it's sleeping or waiting on I/O, then that method that it's calling will throw an InterruptedException.
However, you call interrupt on the current thread after sleep finishes, so this will do nothing but set the "interrupted" status.
You can do one of the following:
Have another Thread call interrupt on that Thread. In run(), let the method complete if an InterruptedException is caught or if interrupted() returns true.
Declare a volatile boolean variable (say, isRunning) that is initialized to true in the created thread. That thread will let the run() method complete if it's false. Have another Thread set it to false at the appropriate time.
t.interrupt() does not actually interrupt the thread immediately it only update interrupt status of thread. If your thread contains method which poll the interrupt status (i.e. sleep )only then the thread will be interrupted otherwise the thread simply complete the execution and interrupt status will be ignored.
Consider following example,
class RunMe implements Runnable {
#Override
public void run() {
System.out.println("Executing :"+Thread.currentThread().getName());
for(int i = 1; i <= 5; i++) {
System.out.println("Inside loop for i = " +i);
}
System.out.println("Execution completed");
}
}
public class Interrupted {
public static void main(String[] args) {
RunMe runMe = new RunMe();
Thread t1 = new Thread(runMe);
t1.start();
t1.interrupt();//interrupt ignored
System.out.println("Interrupt method called to interrupt t1");
}
}
OUTPUT
Interrupt method called to interrupt t1
Executing :Thread-0
Inside loop for i = 1
Inside loop for i = 2
Inside loop for i = 3
Inside loop for i = 4
Inside loop for i = 5
Execution completed
Now just add Thread.sleep(200); in run and you will see the InterruptedException.
Driver.java
public class Driver {
static Object obj = new Object();
public static void main(String [] args) throws InterruptedException
{
Thread thr = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 1: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 1: Completed processing.");
System.out.println("Thread 1: Notifying other waiting threads.");
obj.notify();
}
}
});
Thread thr2 = new Thread(new Runnable(){
#Override
public void run() {
System.out.println("Thread 2: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 2: Completed processing.");
System.out.println("Thread 2: Notifying other waiting threads.");
obj.notify();
}
}
});
thr.start();
thr2.start();
System.out.println("Main Thread: All processing units busy.");
// Thread.sleep(2000); // Enable this and disable the other Thread.sleep(...) and NOW we are good. But again, 'why?' is the question.
synchronized(obj){
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
System.out.println("Main Thread: Found ONLY 1 available slot.");
obj.notify();
obj.wait(); // JVM should catch this as the last request so it has the least priority.
System.out.println("Main Thread: Finished and exiting...");
}
}
}
The code above will not notify the Threads because of the following line:
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
Please take a look at this line in context with the whole class. I am having hard time pinpointing to the reason why this simple proof-of-concept would fail if that line is placed inside ther synchronized block in the Main Thread.
Thank you
The problem is not the sleep but rather that the main thread almost always acquires the lock before one (and occasionally both) of the created threads does. If you print just inside the synchronized blocks it's much more clear what is going on:
synchronized(obj) {
System.out.println("this thread acquired the lock");
You'll see the output is almost always Thread #1, then the main thread, and finally Thread #2 after Thread #1 completes (but main has already returned).
If you run it enough times sometimes both child threads do acquire the lock first and it completes.
The reason moving the sleep to outside the synchronized block in the main thread works is it allows both child threads to reach their respective wait statements.
Read the doc.
Wakes up a single thread that is waiting on this object's
monitor.
If it is sleeping then it is not waiting.
There is other related problem, it is not possible to reach the notify line while the other thread is in the sleep as it keeps the monitor (lock) and the other thread can't run inside the synchronized block. This is always that way as both wait and notify must be run inside related syncrhonized blocks (against the same monitor).
sleep holds the lock, but wait doesn't. so when your main thread is sleeping, both thr and thr2 can't get the lock until main thread notifies them. At that moment, they start to wait and can't receive any notify()
The problem is that sleep does not release the monitor, that is: while the main thread is sleeping, all the other threads cannot enter the synchronized block, so they are basically sleeping with the main thread.
The moment the main thread wakes up, it does notify, but since no one yet entered the wait() position, no one is listening. Then the main thread waits and therefore releases the monitor, so now all threads can proceed to the wait() state, but no one is left to wake them up. -> Deadlock
Here is a sample program in java from tutorials point:
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
The output of the program is as follows.
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
I have trouble understanding why the main thread is executing before the child thread. In the program you can see that first new NewThread() is executed. The NewThread class instantiates a new thread and calls the start() function on the new thread which then calls the run() function.
The loop in the main function comes only after a new thread is created. However when the program is run , The loop in the main thread is run before the child thread. Please help me understand.
The loop in the main thread is run before the child thread. Please help me understand.
Threads do not have any form of synchronization by default and can run in any order with their executions possibly interleaving. You can acquire locks and use those for ensuring order, for example if the main thread acquires the lock before starting the child thread, having the child thread wait to acquire the lock, and having the main thread release the lock once it's done with its tasks.
Thread.start() schedules the thread to be run. After that it's up to the JVM (and the OS) to look after the scheduling. How the threads run is determined by a number of factors including the number of CPUs/cores you have, the OS, the priority etc.
If you need the threads to run in a particular order, wait for each other etc., then you have to use the threading tools provided (synchronisation, locks etc.) Otherwise it's completely arbitrary.