/* * Moonlight|3D Copyright (C) 2005 The Moonlight|3D team * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Created on Nov 2, 2005 */ package ml.core.tasks; /** * \package ml.core.tasks * * This is the basic framework for background tasks. * * This package is part of the core program. */ import java.util.ArrayList; import java.util.List; import ml.core.helper.Observed; /** * This class acts as a manager for background tasks. Once * a task is registered with the manager it is started * automatically and is automatically unregistered once * it is finished. Observers of this task manager are * notified on every change of the list of running * background tasks. * * @author gregor */ public class TaskManager extends Observed { private ArrayList tasks; /** * Helper class to wrap a task in its own thread. * * @author gregor */ private class TaskThread extends Thread { private final Task task; public TaskThread(Task task) { super(); this.task=task; } @Override public void run() { try { task.run(); } catch(Throwable e) { // TODO handle exception here e.printStackTrace(); } removeTask(task); } } public TaskManager() { super(); tasks=new ArrayList(); } /** * Register a new task, start it in a new thread and * notify any observers about that new task. * * @param task the task to be run */ public void addTask(Task task) { synchronized(tasks) { tasks.add(task); TaskThread thread=new TaskThread(task); thread.start(); notifyObservers(); } } /** * Return a list of all tasks that are currently running * @return a list of running tasks */ public List getTasks() { return (ArrayList) tasks.clone(); } /** * Remove a task from the task list and notify any * observers about this change. This does not * stop the background thread. * * @param task the task to remove from the list */ private void removeTask(Task task) { synchronized(tasks) { for (int i = 0; i < tasks.size(); i++) { if (tasks.get(i) == task) { tasks.remove(i); break; } } notifyObservers(); } } }