WorkQueue.java

  1. /*
  2.  * Copyright (C) 2008-2016, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.lib.internal;

  11. import java.util.concurrent.Executors;
  12. import java.util.concurrent.ScheduledThreadPoolExecutor;
  13. import java.util.concurrent.ThreadFactory;

  14. /**
  15.  * Simple work queue to run tasks in the background
  16.  */
  17. public class WorkQueue {
  18.     private static final ScheduledThreadPoolExecutor executor;

  19.     static final Object executorKiller;

  20.     static {
  21.         // To support garbage collection, start our thread but
  22.         // swap out the thread factory. When our class is GC'd
  23.         // the executorKiller will finalize and ask the executor
  24.         // to shutdown, ending the worker.
  25.         //
  26.         int threads = 1;
  27.         executor = new ScheduledThreadPoolExecutor(threads,
  28.                 new ThreadFactory() {
  29.                     private final ThreadFactory baseFactory = Executors
  30.                             .defaultThreadFactory();

  31.                     @Override
  32.                     public Thread newThread(Runnable taskBody) {
  33.                         Thread thr = baseFactory.newThread(taskBody);
  34.                         thr.setName("JGit-WorkQueue"); //$NON-NLS-1$
  35.                         thr.setContextClassLoader(null);
  36.                         thr.setDaemon(true);
  37.                         return thr;
  38.                     }
  39.                 });
  40.         executor.setRemoveOnCancelPolicy(true);
  41.         executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
  42.         executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  43.         executor.prestartAllCoreThreads();

  44.         // Now that the threads are running, its critical to swap out
  45.         // our own thread factory for one that isn't in the ClassLoader.
  46.         // This allows the class to GC.
  47.         //
  48.         executor.setThreadFactory(Executors.defaultThreadFactory());

  49.         executorKiller = new Object() {
  50.             @Override
  51.             protected void finalize() {
  52.                 executor.shutdownNow();
  53.             }
  54.         };
  55.     }

  56.     /**
  57.      * Get the WorkQueue's executor
  58.      *
  59.      * @return the WorkQueue's executor
  60.      */
  61.     public static ScheduledThreadPoolExecutor getExecutor() {
  62.         return executor;
  63.     }
  64. }