/******************************************************************************* * Copyright (c) 2007, 2012 Association for Decentralized Information Management * in Industry THTH ry. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * VTT Technical Research Centre of Finland - initial API and implementation *******************************************************************************/ package org.simantics.browsing.ui.swt.internal; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.simantics.browsing.ui.swt.Activator; /** * Pooled thread work executor for GraphExplorerImpl internal use only. * * Started by {@link Activator}. * * @author Tuukka Lehtonen */ public final class Threads { private static ExecutorService executor; public static synchronized void initialize() { if (executor == null) { initializeExecutor(); } } public static synchronized void shutdown() { if (executor != null) { executor.shutdown(); executor = null; } } private static ExecutorService initializeExecutor() { if (executor == null) { final ThreadGroup tg = new ThreadGroup("GraphExplorer-Worker-Group"); final AtomicInteger counter = new AtomicInteger(0); ThreadFactory tf = new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread t = new Thread(tg, r, "GraphExplorer-Worker-"+(counter.incrementAndGet())); if (!t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } }; // int maxPoolSize = Math.min(Math.max(2, ThreadUtils.CORES), 8); int maxPoolSize = 1; if(maxPoolSize == 1) { executor = Executors.newSingleThreadExecutor(tf); } else { executor = new ThreadPoolExecutor(maxPoolSize / 2, maxPoolSize, // Don't let the threads die too soon 30L, TimeUnit.SECONDS, // LinkedBlockingQueue to allow queueing of tasks // even when all workers are busy. new LinkedBlockingQueue(), tf); } } return executor; } public static ExecutorService getExecutor() { ExecutorService service = executor; if (service == null) throw new IllegalStateException("executor not initialized"); return service; } }