Daemon Java Stream

I am new to concurrency and threads - and used them when developing my application at work. Essentially, I have a series of threads in my RMI application (a server-side component) that polls file changes (these files are updated every few seconds).

When testing in the dev block, I start the server from the command line and then close it manually when it is finished, and rinses and repeats throughout the day.

As it turns out, I think that my threads may not stop when I close the command line and continue processing. This leads to some very bad side effects - although I'm not 100% sure if this is possible, so hopefully someone can confirm that it could be so.

If I create a thread with daemons - does this mean that when I close the command line - will these threads automatically stop? I need to somehow terminate the application nicely, but since the server will eventually be started using autosys, I'm not sure if the best way is to make all threads complete when shutting down

thank

+5
source share
3 answers

The following code demonstrates creating a thread pool with a fictitious task running, this task is then launched, and when the application terminates, a stop hook is triggered, which cancels all tasks that are performed and closes the thread pool cleanly.

You do not need to use Callable, like me, you can use Runnables and the threadPool.execute method and just terminate 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();
        }
    });

. Java EE javax.servlet.ServletContextListener

+1

Java. JVM, . JVM, : .

+1

RMI Runtime creates threads that you cannot stop. The only way to disable the service is with System.exit ().

I do this in a separate thread. After: new ShutThread (). Start (), the terminating thread waits 2 seconds to give any lingering messages a chance to complete the journey, and then issues System.exit ().

0
source

All Articles