1 /*******************************************************************************
2 * Copyright (c) 2007, 2018 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 * Semantum Oy - added shutdown facilities
12 *******************************************************************************/
14 package org.simantics.utils.threads;
16 import java.util.concurrent.Callable;
17 import java.util.concurrent.ScheduledFuture;
18 import java.util.concurrent.ScheduledThreadPoolExecutor;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.atomic.AtomicInteger;
23 * @author Toni Kalajainen
24 * @author Tuukka Lehtonen
26 public class ExecutorWorker {
28 private static volatile ExecutorWorker instance;
30 public static ExecutorWorker getInstance() {
31 if (instance == null) {
32 synchronized (ExecutorWorker.class) {
34 instance = new ExecutorWorker();
40 private ExecutorWorker() {}
42 private final AtomicInteger counter = new AtomicInteger(0);
43 private final ThreadGroup threadGroup = new ThreadGroup("ExecutorWorker-Group");
44 private ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1, r -> {
45 Thread t = new Thread(threadGroup, r, "ExecutorWorker-" + (counter.incrementAndGet()));
48 if (t.getPriority() != Thread.NORM_PRIORITY)
49 t.setPriority(Thread.NORM_PRIORITY);
53 public synchronized ScheduledFuture<Object> timerExec(final Executable executable, int delay)
55 Callable<Object> c = () -> {
56 ThreadUtils.asyncExec(executable.threadAccess, executable.runnable);
59 return pool.schedule(c, delay, TimeUnit.MILLISECONDS);
62 private void shutdownThis() {
63 ScheduledThreadPoolExecutor e = pool;
66 ThreadUtils.shutdownAndAwaitTermination(e, 1000);
70 public static synchronized void shutdown() {
71 ExecutorWorker i = instance;