1 /******************************************************************************* 2 * Copyright (c) 2006, 2018 Cognos Incorporated 3 * 4 * This program and the accompanying materials 5 * are made available under the terms of the Eclipse Public License 2.0 6 * which accompanies this distribution, and is available at 7 * https://www.eclipse.org/legal/epl-2.0/ 8 * 9 * SPDX-License-Identifier: EPL-2.0 10 * 11 * Contributors: 12 * Cognos Incorporated - initial API and implementation 13 *******************************************************************************/ 14 package org.eclipse.equinox.internal.cm; 15 16 import java.util.LinkedList; 17 18 /** 19 * SerializedTaskQueue is a utility class that will allow asynchronous but serialized execution of tasks 20 */ 21 public class SerializedTaskQueue { 22 23 private static final int MAX_WAIT = 5000; 24 private final LinkedList<Runnable> tasks = new LinkedList<>(); 25 private Thread thread; 26 private final String queueName; 27 SerializedTaskQueue(String queueName)28 public SerializedTaskQueue(String queueName) { 29 this.queueName = queueName; 30 } 31 put(Runnable newTask)32 public synchronized void put(Runnable newTask) { 33 tasks.add(newTask); 34 if (thread == null) { 35 thread = new Thread(queueName) { 36 @Override 37 public void run() { 38 Runnable task = nextTask(MAX_WAIT); 39 while (task != null) { 40 task.run(); 41 task = nextTask(MAX_WAIT); 42 } 43 } 44 }; 45 thread.start(); 46 } else 47 notify(); 48 } 49 nextTask(int maxWait)50 synchronized Runnable nextTask(int maxWait) { 51 if (tasks.isEmpty()) { 52 try { 53 wait(maxWait); 54 } catch (InterruptedException e) { 55 // ignore -- we control the stack here and do not need to propagate it. 56 } 57 58 if (tasks.isEmpty()) { 59 thread = null; 60 return null; 61 } 62 } 63 return tasks.removeFirst(); 64 } 65 } 66