0

I have a manager class that allows sub-modules to register a shutdown-hook using Runnable.

public class ApplicationManager() {
    private final List<Runnable> shutdownHooks;

    private ApplicationManager() {
        // Other stuff

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (shutdownHooks != null && !shutdownHooks.isEmpty()) {
                shutdownHooks.parallelStream()
                             .forEach(Runnable::run);
            }
        }));
    }

    // Other singleton stuff

    public void registerShutdownHook(final Runnable hook) {
        if (hook != null) {
            this.shutdownHooks.add(hook);
        }
    }

    public void resetApplication() {
        // Reset stuff

        shutdownHooks.parallelStream()
                     .forEach(Runnable::run);
        shutdownHooks.clear();
    }
}

The reason why this class does not accept Thread instances in registerShutdownHook() was mainly to reduce the complexity for the caller (so they do not need to wrap in an instance of Thread).

The application can be resetted, and I want to clean up the application by executing all the shutdown hooks. Although, I could wrap each Runnable with a Thread, register all of them with Runtime during registerShutdownHook(), and remove them from Runtime when resetApplication() is called, but I thought it may be neater that I control what needs to run.

In order to speed things up during cleanup, I used parallelStream(). Now I'm wondering if that is a bad idea to (during shutdown hook):

  1. Use the thread pool;
  2. Alternatively, create more threads.

Anyone experienced enough to give an advice?

Jai
  • 8,165
  • 2
  • 21
  • 52
  • You might have some issues with parallel execution if some hooks depend on others and/or access shared variables without synchronization – Ivan May 24 '18 at 03:43
  • @Ivan Other than that this shouldn't cause any problem? – Jai May 24 '18 at 04:32

0 Answers0