Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

daemon

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

like image 907
M.J. Avatar asked Dec 22 '22 12:12

M.J.


2 Answers

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.

like image 190
Costi Ciudatu Avatar answered Dec 24 '22 01:12

Costi Ciudatu


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.

like image 33
Dorus Avatar answered Dec 24 '22 01:12

Dorus