Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Daemon thread Java [duplicate]

I am a new to concurrency and threads - and have been using them when developing my application at work. Essentially i have a number of threads in my RMI application (server side component) that poll changes in files (these files update every few seconds) .

When testing on a dev box I have been running the server from the command line and then closing it manually when finished and rinse and repeat throughout the day.

As it transpires - I think my threads may not be stopping when i shut the command line and still carry on processing. This is leading to some very bad side effects - although I am not 100% sure if this is possible so hopefully someone can confirm this might be the case.

If i make a thread a daemon - does this mean that when i shut the command line - these threads will automatically stop? I need some way of terminating the application nicely but because the server will eventually be run by autosys I am not sure whats the best way to make all threads finish when shut down

Thanks

like image 756
Biscuit128 Avatar asked Mar 17 '13 17:03

Biscuit128


People also ask

Can we start a thread two times in Java?

No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.

Can a thread spawn another thread Java?

Yes a thread can launch another thread, and that thread can launch thread(s) and on and on... In the run() method of a thread - you can create and start other threads.

Are Java threads daemon by default?

Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by ...

What will happen if two threads try to modify same resource without synchronization in Java?

A: When more than one thread try to access same resource without synchronization causes race condition. So we can solve race condition by using either synchronized block or synchronized method.


2 Answers

Threads run inside a Java Virtual Machine. If you stop the JVM, the threads don't run anymore. You could see exiting the JVM as pulling the plug off your computer: nothing can run anymore.

like image 121
JB Nizet Avatar answered Sep 24 '22 02:09

JB Nizet


The following code demonstrates creating a thread pool with a dummy running task, that task is then started and when the application is terminated, a shutdown hook runs which cancels all running tasks and cleanly closes the thread pool.

You do not have to use Callable's as I have, you can use Runnables and the threadPool.execute method and simply terminate the threadPool which is a little less elegant.

    final ExecutorService threadPool = Executors.newCachedThreadPool();
    final List<Future<Void>> runningTasks = new ArrayList<>();
    Future<Void> task = threadPool.submit(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            int count = 0;
            while(true) {
                System.out.println(++count);
                Thread.sleep(1000);
            }
        }
    });
    runningTasks.add(task);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            for(Future<Void> runningTask : runningTasks) {
                runningTask.cancel(true);
            }
            threadPool.shutdownNow();
        }
    });

Shutdown hooks are for standalone applications. In a Java EE container, you could do the same with a javax.servlet.ServletContextListener

like image 21
JayTee Avatar answered Sep 21 '22 02:09

JayTee