001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.progress.swing;
003
004import java.util.concurrent.CancellationException;
005import java.util.concurrent.ExecutionException;
006import java.util.concurrent.Future;
007import java.util.concurrent.LinkedBlockingQueue;
008import java.util.concurrent.ThreadPoolExecutor;
009import java.util.concurrent.TimeUnit;
010
011import org.openstreetmap.josm.tools.Logging;
012import org.openstreetmap.josm.tools.Utils;
013import org.openstreetmap.josm.tools.bugreport.BugReport;
014
015/**
016 * Executor that displays the progress monitor to the user.
017 * <p>
018 * Similar to Executors.newSingleThreadExecutor(), but displays the
019 * progress monitor whenever a new task is executed.
020 * @since 12675 (moved from {@code gui.progress} package}
021 */
022public class ProgressMonitorExecutor extends ThreadPoolExecutor {
023
024    /**
025     * Creates a new {@code ProgressMonitorExecutor}
026     * @param nameFormat see {@link Utils#newThreadFactory(String, int)}
027     * @param threadPriority see {@link Utils#newThreadFactory(String, int)}
028     */
029    public ProgressMonitorExecutor(final String nameFormat, final int threadPriority) {
030        super(1, 1, 0L, TimeUnit.MILLISECONDS,
031                new LinkedBlockingQueue<>(),
032                Utils.newThreadFactory(nameFormat, threadPriority));
033    }
034
035    @Override
036    public void execute(Runnable command) {
037        if (PleaseWaitProgressMonitor.currentProgressMonitor != null) {
038            //TODO show only if this can't be in background or better if always in background is not checked
039            PleaseWaitProgressMonitor.currentProgressMonitor.showForegroundDialog();
040        }
041        super.execute(command);
042    }
043
044    @Override
045    public void afterExecute(final Runnable r, Throwable t) {
046        // largely as proposed by JDK8 docs
047        super.afterExecute(r, t);
048        if (t == null && r instanceof Future<?>) {
049            try {
050                ((Future<?>) r).get();
051            } catch (CancellationException cancellationException) {
052                Logging.debug("Thread {0} raised {1}", Thread.currentThread().getName(), cancellationException);
053            } catch (ExecutionException executionException) {
054                Logging.trace(executionException);
055                t = executionException.getCause();
056            } catch (InterruptedException interruptedException) {
057                Thread.currentThread().interrupt(); // ignore/reset
058            }
059        }
060        if (t != null) {
061            Logging.error("Thread {0} raised {1}", Thread.currentThread().getName(), t);
062            BugReport.addSuppressedException(t);
063        }
064    }
065}