View Javadoc
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  
11  package org.eclipse.jgit.lib.internal;
12  
13  import java.util.concurrent.Executors;
14  import java.util.concurrent.ScheduledThreadPoolExecutor;
15  import java.util.concurrent.ThreadFactory;
16  
17  /**
18   * Simple work queue to run tasks in the background
19   */
20  public class WorkQueue {
21  	private static final ScheduledThreadPoolExecutor executor;
22  
23  	static final Object executorKiller;
24  
25  	static {
26  		// To support garbage collection, start our thread but
27  		// swap out the thread factory. When our class is GC'd
28  		// the executorKiller will finalize and ask the executor
29  		// to shutdown, ending the worker.
30  		//
31  		int threads = 1;
32  		executor = new ScheduledThreadPoolExecutor(threads,
33  				new ThreadFactory() {
34  					private final ThreadFactory baseFactory = Executors
35  							.defaultThreadFactory();
36  
37  					@Override
38  					public Thread newThread(Runnable taskBody) {
39  						Thread thr = baseFactory.newThread(taskBody);
40  						thr.setName("JGit-WorkQueue"); //$NON-NLS-1$
41  						thr.setContextClassLoader(null);
42  						thr.setDaemon(true);
43  						return thr;
44  					}
45  				});
46  		executor.setRemoveOnCancelPolicy(true);
47  		executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
48  		executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
49  		executor.prestartAllCoreThreads();
50  
51  		// Now that the threads are running, its critical to swap out
52  		// our own thread factory for one that isn't in the ClassLoader.
53  		// This allows the class to GC.
54  		//
55  		executor.setThreadFactory(Executors.defaultThreadFactory());
56  
57  		executorKiller = new Object() {
58  			@Override
59  			protected void finalize() {
60  				executor.shutdownNow();
61  			}
62  		};
63  	}
64  
65  	/**
66  	 * Get the WorkQueue's executor
67  	 *
68  	 * @return the WorkQueue's executor
69  	 */
70  	public static ScheduledThreadPoolExecutor getExecutor() {
71  		return executor;
72  	}
73  }