How to categorise a daemon thread to specific thread? - java

I have 3 threads called T1 , T2 and T3 and also i have 3 daemon threads like dt1, dt2 and dt3.
I want to (assign) provide a service dt1 to thread T1 , dt2 to thread T2 and dt3 to thread T3.
when threads T1,T2 and T3 complete their runnable task it's related daemon thread also got closed internally.
Can any one please tell me how to do it in java using thread daemon concept?

"Daemon thread" is not a concept - it's just a feature of Java threads. When a JVM is terminating, it waits for non-daemon threads to terminate by themselves. On the contrary, daemon threads just get terminated no matter what they're doing.
Leaving that behind, one idea might be to establish a "shutdown" flag inside your "daemon" thread. When the non-daemon thread terminates, it could set that flag to true. The daemon thread would check the flag and terminate once it's true. Remember to synchronize that mechanism properly, e.g. by using the volatile keyword.

So, if I understand your question correctly, you want each 'work thread' T1..T3 to have its own background thread (dt1…dt3) doing some co-processing, and you want the background thread to exit when your main thread exits, yes? You could do something like this:
Make each 'main thread T1… a Runnable that looks like this, so that when you launch your T1, it launches its own dt1, and then asks it to shutdown (via interrupt()) when it finishes.
#Override
public void run() {
ExecutorService e = Executors.newSingleThreadExecutor();
Runnable r = new Runnable() {
#Override
public void run() {
// this is your deamon thread
boolean done = false;
while (!done && !Thread.currentThread().isInterrupted()){
// Do your background deamon stuff here.
//
// Try not to use blocking, uninterruptible methods.
//
/* If you call a method that throws an interrupted exception,
* you need to catch that exception and ignore it (or set done true,)
* so the loop will terminate. If you have other exit conditions,
* just set done=true in this body */
}
}
};
e.execute(r); // launch your daemon thread
try {
// do your main stuff here
}
finally {
e.shutdownNow(); // this will 'interrupt' your daemon thread when run() exits.
}
}

Related

State of thread while in run() method (Java)

I am trying to understand multithreading in java. As I was going through the various states a Java thread can be in (new, Runnable, Running, Waiting/Blocked, Dead). I tried to run some simple code to check the states of the thread.
I created a class MyThread that extends Thread and overrode run() method.
package com.practice.threads;
public class MyThread extends Thread {
#Override
public void run() {
super.run();
System.out.println("Running Mythread.");
System.out.println("State of thread : " + this.getState()); // line 2
}
}
Now I have created a simple class to test the states of thread :
package com.practice.threads;
public class ThreadStateDemo {
/**
* #param args
*/
public static void main(String[] args) {
MyThread myThread = new MyThread();
System.out.println("State of thread : " + myThread.getState()); // line 1
myThread.start();
}
}
Running this class give the following output :
State of thread : NEW
Running Mythread.
State of thread : RUNNABLE
The output of line 2 is something I don't understand. When run() method of a thread instance is being executed, how can it be in RUNNABLE state? I saw mention of a RUNNING state in a book (SCJP Suncertified Programmer). Should it not show RUNNING?
The book has an (easy-to-make) error, the state is RUNNABLE, not RUNNING. There is no RUNNING state, see the JavaDoc:
NEW
A thread that has not yet started is in this state.
RUNNABLE
A thread executing in the Java virtual machine is in this state.
BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
TERMINATED
A thread that has exited is in this state.
(My emphasis)
It's just an odd, slightly pedantic name, since technically, it's only running if the OS is running it. But it's "running" from the JVM's point of view.
The JVM doesn't control whether the thread is running or not, the OS does. The JVM only knows if it asked the OS to run the thread which is what makes it RUNNABLE.

Deamon thread not working T1,T2,T3 are the classes. I wrote separately. What mistake did I make? Why is my deamon thread not reachable?

My code:
package multithreading;
public class JoinT1T2T3 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Daemon thread is running");
}
else
{
System.out.println("Slave thread");
}
}
public static void main(String args[])
{
Thread t=new Thread();
t.setDaemon(true);
T1 thread1=new T1();
T2 thread2=new T2();
T3 thread3=new T3();
System.out.println("First Thread name is::: "+thread1.getName());
thread1.setName("XXXXXXXXXX");
System.out.println("First Thread After changing name::: "+thread1.getName());
System.out.println("First thread's id is :::"+thread1.getId());
thread1.start();
try
{
thread1.join(3000);
}
catch(Exception e)
{
System.out.println("-----------");
}
//thread2.start();
thread2.start();
thread3.start();
}
}
Why is my daemon not reachable? Please provide me an explanation and code.
T1,T2,T3 are three different classes. The main method is also the run method. I created a new thread instance. Still getting "code not reachable". Which is if{} else{} in run method.
You are getting the "not reachable" error because JoinT1T2T3#run() is never called anywhere.
To Reach JoinT1T2T3#run()
In order for a run() method to be called, an object of its containing class should be explicitly passed to a Thread at construction-time using Thread#(Runnable). For example:
Thread t = new Thread(new JoinT1T2T3());
Now, Thread t will call JoinT1T2T3#run() whenever it starts.
To Run t
Even if t is a daemon, it must still be start()'ed just like any other Thread, or else it will not run. (and thus JoinT1T2T3#run() will never be called) So you need to do this:
Thread t = new Thread(new JoinT1T2T3());
t.setDaemon(true);
t.start();
explaining "daemon" threads
Generally speaking, in Java the only functional difference between a deamon Thread and a non-daemon Thread is that "the Java Virtual Machine exits when the only threads running are all daemon threads" (source). Other than that, a daemon Thread behaves exactly like a non-daemon Thread, syntax and all. It must still be constructed with a Runnable and start()'ed, just like any other Thread.
However, because a daemon thread may be abruptly terminated when the JVM exits, daemons should be used sparingly. In particular, daemons should not be used for any I/O or resource cleanup. "Normal" guarantees about stuff like finally blocks and stack unwinding don't necessarily apply to daemon threads--if the JVM decides to exit, all daemons are immediately abandoned. (source)
Java daemons should be used only for background housekeeping, bookkeeping, metrics, non-critical monitoring, etc.

Java Runnables start running before they are called

I have a function whose output is processed by multiple threads (created after the function call occurs). But when I run the program I receive a NullPointerException from the thread before the function is finished running. How do I specify for Java not to start the threads early?
public class MainThread extends Thread {
public MainClass() {
...
myRunnable1 = new myRunnable(args[]);
myRunnable2 = new myRunnable(args[]);
...
}
public void run() {
for (someNumberOfRuns) {
function1();
System.out.println("Done");
thread1 = new Thread(myRunnable);
thread2 = new Thread(myRunnable);
thread1.start();
thread2.start();
...
}
}
}
On the first iteration through the for loop, both thread1 and thread2 will throw NullPointException errors, then the system will print out "Done". Does anyone know why the two threads are starting before their respective start() calls in the method?
Thanks.
(Java version is 1.6u26)
Does anyone know why the two threads are starting before their respective start() calls in the method?
This does not happen under Java -- if the thread is being started then some code is starting it. I suspect that you are either calling the run() method directly in the thread that instantiates MainThread or you are calling start() in some place that you aren't expecting.
It may help if you use a debugger and put a breakpoint in the run() method to see who is calling it. If you want to use println debugging you could print out an exception that shows the stack trace inside of run():
new Throwable().printStackTrace();
If you provide the code that actually instantiates the MainThread we may be able to help you more.
If you are asking how to make a bunch of threads all wait to be started at the same time,
Have each thread execute a Runnable, and have the first line of run() be
barrier.await(LONG_TIMEOUT_MS, TimeUnit.MILLISECONDS);
where barrier is defined as
final CyclicBarrier barrier = new CyclicBarrier(numThreads + 1);
Then when you're ready for all of them to start, call
// Wait for all threads to be ready, then start them all at once
barrier.await(LONG_TIMEOUT_MS, TimeUnit.MILLISECONDS);
A timeout indicates that one of your threads did not execute withing the given time.

Java Thread synchronization

Is there a way for a thread that starts a new thread to wait until the thread it started has stopped? I was thinking about using locked, but then if the thread crashes, the lock will never get release.
so when my program calls
cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
will it wait until the thread is finished?
mPlayerList.WaitForAllPlayers();
do
{
do
{
r=GetClient();
switch(r)
{
case 0: return; // exitvon a very bad error
}
} while(r==2); // loop if it was a timeout wait for this thread to terminate.
cTurnCardOvrerConnection thread = new cTurnCardOvrerConnection("thread3", connection, mPlayerList, mPlayersMessages, lBoard);
if ( CheckTimeStamp())
break;
} while( mPlayerList.AllPlayersFinished()==false);
you can just use Thread.join().
of course, if the primary thread is just launching the secondary thread and then waiting for it to finish, there's really no use for the secondary thread (just do the work on the primary thread).
Try using a CountDownLatch.

How to keep my program alive for as long a daemon thread is running?

I have a requirement, that I want to start a poller once which will run foreever until the machine is restarted or the process is being killed. Now, I tried to start the poller from a main method using a shell script, but the problem is that as soon as the main method completed its execution, the poller also stoped working, as i am not using any servers to achieve so.
I heard something about daemon threads, but I am wondering how to create a daemon thread, which will run forever, and help my poller to run also.
UPDATE:
public class SomeThread extends Thread {
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
unitPoller.doPolling();
}
public static void main(String[] args) {
SomeThread someThread = new SomeThread();
someThread.setDaemon(true);
someThread.start();
}
}
Above is my updated class, now whenever I execute this thread from the main method, it creates a thread but as soon as the execution of main method completes, my poller stops working, as the JVM shuts down.
With this problem, what should i do.
Thanks
You just create a thread and call th.setDaemon(true) before calling th.start().
Edit:
The above answers the question "how to create a daemon thread", but (as the scope of the question has changed), a proper answer would be: don't create a daemon thread if you want your thread to keep the JVM from exiting once the main thread completed.
1) You need someThread.setDaemon(false) instead of 'true'. A daemon thread actualy does NOT stop java from shutting down.
From the javadoc:
void java.lang.Thread.setDaemon(boolean on)
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be called before the thread is started.
2) I think it's not your main, but your run() method that finishes to soon. Try to put a while (true) loop around your doPolling method.
#Override
public void run() {
UnitPoller unitPoller = new UnitPoller();
while (true)
unitPoller.doPolling();
}
3) It's cleaner to call join() inside the main then to rely on daemon thread behavior.
try {
someThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
4) If you need a clean way to shut down the deamonthread. Consider implementing InterruptedException to exit the polling task. You can also use the shutdown hook.
The term "daemon thread" in Java is a bit misleading, as it really means "that thread is not supposed to keep the JVM alive". This means that the JVM will shut down as soon as the last non-daemon thread terminated (as you already stated in your question).
What you are possibly looking for is the Apache Commons Daemon project, which allows to create nice "system services", started through /etc/init.d/ entries and all. This works on Windows and *nix systems.

Categories