package org.hwo.tasklet; import java.util.LinkedList; import java.util.List; public class TaskletManager { private static TaskletManager _TaskletManager = new TaskletManager(); public static TaskletManager instance(){ return _TaskletManager; } List taskletListeners; List taskletThreads; List tasklets; int threads; boolean shuttingDown; public TaskletManager(){ taskletListeners = new LinkedList(); taskletThreads = new LinkedList(); tasklets = new LinkedList(); threads = 1; } public synchronized void addTaskletListener(TaskletListener listener){ taskletListeners.add(listener); } public synchronized void removeTaskletListener(TaskletListener listener){ taskletListeners.remove(listener); } public synchronized int getThreads() { return threads; } public synchronized void setThreads(int threads) { this.threads = threads; } public synchronized void fireTaskletQueued(Tasklet tasklet){ for (TaskletListener l:taskletListeners) l.taskletQueued(this, tasklet); } public synchronized void fireTaskletStarted(Tasklet tasklet){ for (TaskletListener l:taskletListeners) l.taskletStarted(this, tasklet); } public synchronized void fireTaskletFinished(Tasklet tasklet){ for (TaskletListener l:taskletListeners) l.taskletFinished(this, tasklet); } public synchronized void fireTaskletProgressChanged(Tasklet tasklet){ for (TaskletListener l:taskletListeners) l.taskletProgressChanged(this, tasklet); } public synchronized void enqueue(Tasklet tasklet){ if (taskletThreads.size() < threads){ taskletThreads.add(new TaskletThread(this)); } tasklets.add(tasklet); fireTaskletQueued(tasklet); this.notify(); } public synchronized Tasklet pop(){ if (tasklets.size()>0) return tasklets.remove(0); return null; } public int getThreadPoolSize(){ return taskletThreads.size(); } public void shutdown(){ synchronized (this) { shuttingDown = true; setThreads(0); } while (taskletThreads.size() > 0){ try { Thread.sleep(50); synchronized (this) { this.notifyAll(); } } catch (InterruptedException ex){ ex.printStackTrace(); } } } public boolean isShuttingDown() { return shuttingDown; } public synchronized void removeTaskletThread(TaskletThread taskletThread){ taskletThreads.remove(taskletThread); } private Tasklet findTasklet(){ for (TaskletThread thread: this.taskletThreads){ if (Thread.currentThread().equals(thread)){ return thread.getCurrentTasklet(); } } return null; } public synchronized void setProgress(double percentage){ setProgress(String.format("%d%%", new Double(percentage * 100).intValue())); } public synchronized void setProgress(String progress){ Tasklet c = findTasklet(); if (c != null){ c.setProgress(progress); fireTaskletProgressChanged(c); } } }