Advertisement
Guest User

WorkUnit

a guest
Oct 31st, 2012
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.27 KB | None | 0 0
  1. // Implemented as a solution to the question in: http://stackoverflow.com/questions/13005964/thread-pool-where-workers-are-both-producers-and-consumers
  2.  
  3. public class WorkUnit implements Runnable, Comparable<WorkUnit> {
  4.    
  5.     // the maximum and actual time in ms this job will spend simulating processing
  6.     private long maxJobTimeMS, processingTime;
  7.    
  8.     // an integer to specify the maximum number of other work units this one may spawn
  9.     private int maxBranchingFactor;
  10.    
  11.     // an executor to schedule new jobs to
  12.     private TestExecutor executor;
  13.  
  14.     public WorkUnit(long maxJobTimeMS, int maxBranchingFactor, TestExecutor executor) {
  15.         this.maxJobTimeMS = maxJobTimeMS;
  16.         this.maxBranchingFactor = maxBranchingFactor;
  17.         this.executor = executor;
  18.         this.processingTime = randomLong(this.maxJobTimeMS);
  19.     }
  20.  
  21.     public void run() {
  22.         // simulate some processing time
  23.         try {
  24.             Thread.sleep(this.processingTime);
  25.             System.out.println(this.toString() + " took " + this.processingTime + "ms.");
  26.         }
  27.         catch(InterruptedException e) {
  28.             if(executor.awaitCompletionTimedOut()) {
  29.                 terminateWork();
  30.             }
  31.         }
  32.        
  33.         // submit a random number of new jobs up to a maximum branching factor before completion
  34.         int newJobCount = (int)randomLong(this.maxBranchingFactor);
  35.         while(newJobCount-- > 0 && !executor.awaitCompletionTimedOut()) {
  36.             long newWaitTime = randomLong(this.maxJobTimeMS);
  37.             System.out.println(this.toString() + " generated a new job which will take: " + newWaitTime + "ms.");
  38.             this.executor.executeJob(new WorkUnit(maxJobTimeMS, maxBranchingFactor, executor));
  39.         }
  40.     }
  41.    
  42.     private void terminateWork() {
  43.         System.out.println(this.toString() + " has been interrupted and encountered a timeout; exiting...");
  44.     }
  45.    
  46.     private long randomLong(long max) {
  47.         return Math.round(Math.random() * (double)max);
  48.     }
  49.    
  50.     public int compareTo(WorkUnit o) {
  51.         if(this == o) {
  52.             return 0;
  53.         }
  54.         // example job ordering: here, short jobs over longer ones
  55.         return Long.compare(this.processingTime, o.processingTime);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement