001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.spi.lifecycle;
003
004import java.util.List;
005import java.util.Objects;
006import java.util.concurrent.ExecutionException;
007import java.util.concurrent.ExecutorService;
008import java.util.concurrent.Executors;
009import java.util.concurrent.Future;
010
011import org.openstreetmap.josm.tools.JosmRuntimeException;
012import org.openstreetmap.josm.tools.Logging;
013import org.openstreetmap.josm.tools.Utils;
014import org.openstreetmap.josm.tools.bugreport.BugReport;
015
016/**
017 * JOSM lifecycle.
018 * @since 14125
019 */
020public final class Lifecycle {
021
022    private static volatile InitStatusListener initStatusListener;
023
024    private static volatile Runnable shutdownSequence;
025
026    private Lifecycle() {
027        // Hide constructor
028    }
029
030    /**
031     * Gets initialization task listener.
032     * @return initialization task listener
033     */
034    public static InitStatusListener getInitStatusListener() {
035        return initStatusListener;
036    }
037
038    /**
039     * Sets initialization task listener.
040     * @param listener initialization task listener. Must not be null
041     */
042    public static void setInitStatusListener(InitStatusListener listener) {
043        initStatusListener = Objects.requireNonNull(listener);
044    }
045
046    /**
047     * Gets shutdown sequence.
048     * @return shutdown sequence
049     * @since 14140
050     */
051    public static Runnable getShutdownSequence() {
052        return shutdownSequence;
053    }
054
055    /**
056     * Sets shutdown sequence.
057     * @param sequence shutdown sequence. Must not be null
058     * @since 14140
059     */
060    public static void setShutdownSequence(Runnable sequence) {
061        shutdownSequence = Objects.requireNonNull(sequence);
062    }
063
064    /**
065     * Initializes the main object. A lot of global variables are initialized here.
066     * @param initSequence Initialization sequence
067     * @since 14139
068     */
069    // PMD wasn't detecting that we were trying to shutdown the ExecutorService
070    @SuppressWarnings("PMD.CloseResource")
071    public static void initialize(InitializationSequence initSequence) {
072        // Initializes tasks that must be run before parallel tasks
073        runInitializationTasks(initSequence.beforeInitializationTasks());
074
075        // Initializes tasks to be executed (in parallel) by a ExecutorService
076        try {
077            ExecutorService service = Executors.newFixedThreadPool(
078                    Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
079            for (Future<Void> i : service.invokeAll(initSequence.parallelInitializationTasks())) {
080                i.get();
081            }
082            // asynchronous initializations to be completed eventually
083            initSequence.asynchronousRunnableTasks().forEach(x -> {
084                if (x != null) service.submit(x);
085            });
086            initSequence.asynchronousCallableTasks().forEach(x -> {
087                if (x != null) service.submit(x);
088            });
089            try {
090                service.shutdown();
091            } catch (SecurityException e) {
092                Logging.log(Logging.LEVEL_ERROR, "Unable to shutdown executor service", e);
093            }
094        } catch (InterruptedException ex) {
095            Thread.currentThread().interrupt();
096            throw new JosmRuntimeException(ex);
097        } catch (ExecutionException ex) {
098            throw new JosmRuntimeException(ex);
099        }
100
101        // Initializes tasks that must be run after parallel tasks
102        runInitializationTasks(initSequence.afterInitializationTasks());
103    }
104
105    private static void runInitializationTasks(List<InitializationTask> tasks) {
106        for (InitializationTask task : tasks) {
107            try {
108                task.call();
109            } catch (JosmRuntimeException e) {
110                // Can happen if the current projection needs NTV2 grid which is not available
111                // In this case we want the user be able to change his projection
112                BugReport.intercept(e).warn();
113            }
114        }
115    }
116
117    /**
118     * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
119     * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
120     * @param exitCode The return code
121     * @return {@code true}
122     * @since 14140
123     */
124    public static boolean exitJosm(boolean exit, int exitCode) {
125        if (shutdownSequence != null) {
126            shutdownSequence.run();
127        }
128
129        if (exit) {
130            System.exit(exitCode);
131        }
132        return true;
133    }
134}