package csci3366sample.masterworker; import java.io.Serializable; import java.util.List; import java.util.LinkedList; import java.util.Random; /** * Classes for "fake" tasks for generic master/worker example. * (Tasks just sleep for specified number of milliseconds rather than * doing anything useful, and produce an equally fake result -- true/false * reflecting whether Thread.sleep was interrupted, which it should not be.) * * Main class here consists of static convenience methods. * Nested classes Task and TaskResult represent tasks and results. * Nested class SynchTaskQueue is a stripped-down thread-safe queue, * containing only the functionality needed for classes that use it. */ public class FakeTasks { private static final long SEED = 4321; /** * Build list of tasks with randomly-generated times. * Uses a fixed seed for consistent results from run to run. */ public static List randomTasks(int numTasks, int maxTaskTime) { Random randGen = new Random(SEED); List taskQueue = new LinkedList(); for (int i = 0; i < numTasks; ++i) { // generate integer in range 1 .. maxTaskTime taskQueue.add(new Task(randGen.nextInt(maxTaskTime)+1)); } return taskQueue; } /** * Produce string for task and result for verbose printing. */ public static String toString(Task t, TaskResult tr) { return "task with time = " + t.time + " " + (tr.completed ? "(processed)" : "(interrupted)"); } /** * Class for tasks. * Serializable so they can be sent over sockets. */ public static class Task implements Serializable { private static final long serialVersionUID = 1L; public final int time; public Task(int t) { time = t; } public TaskResult execute() { try { Thread.sleep(time); return new TaskResult(true); } catch (InterruptedException e) { return new TaskResult(false); } } } /** * Class for task results. * Serializable so they can be sent over sockets. */ public static class TaskResult implements Serializable { private static final long serialVersionUID = 1L; public final boolean completed; public TaskResult(boolean c) { completed = c; } } /** * Class for thread-safe queue of tasks, containing only * functionality needed for classes that use it. */ public static class SynchTaskQueue { private List tasks; /** Constructor. */ public SynchTaskQueue(List _tasks) { tasks = _tasks; } /** Check whether queue is empty. */ public synchronized boolean isEmpty() { return tasks.isEmpty(); } /** Get a task (returns null if queue is empty). */ public synchronized FakeTasks.Task get() { if (tasks.isEmpty()) { notifyAll(); return null; } else { return tasks.remove(0); } } } }