/** * Constructs a new DistThreadPool. * * @param strategy for job processing. * @param size of the pool. * @param mfile machine file. */ public DistThreadPool(StrategyEnumeration strategy, int size, String mfile) { this.strategy = strategy; if (size < 0) { this.threads = 0; } else { this.threads = size; } if (mfile == null || mfile.length() == 0) { this.mfile = DEFAULT_MFILE; } else { this.mfile = mfile; } jobstack = new LinkedList<Runnable>(); // ok for all strategies ? try { ec = new ExecutableChannels(this.mfile); } catch (FileNotFoundException e) { e.printStackTrace(); throw new IllegalArgumentException("DistThreadPool " + e); } if (debug) { logger.debug("ExecutableChannels = " + ec); } try { ec.open(threads); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("DistThreadPool " + e); } if (debug) { logger.debug("ExecutableChannels = " + ec); } workers = new DistPoolThread[0]; }
/** Terminates the threads. */ public void terminate() { while (hasJobs()) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } for (int i = 0; i < workers.length; i++) { try { while (workers[i].isAlive()) { workers[i].interrupt(); workers[i].join(100); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } ec.close(); }
/** Run the thread. */ @Override public void run() { logger.info("ready, myId = " + myId); Runnable job; int done = 0; long time = 0; long t; boolean running = true; while (running) { try { logger.debug("looking for a job"); job = pool.getJob(); working = true; if (debug) { logger.info("working " + myId + " on " + job); } t = System.currentTimeMillis(); // send and wait, like rmi try { if (job instanceof ShutdownRequest) { ec.send(myId, ExecutableServer.STOP); } else { ec.send(myId, job); } logger.info("send " + myId + " at " + ec + " send job " + job); } catch (IOException e) { e.printStackTrace(); logger.info("error send " + myId + " at " + ec + " e = " + e); working = false; } // job.run(); Object o = null; try { if (working) { logger.info("waiting " + myId + " on " + job); o = ec.receive(myId); logger.info("receive " + myId + " at " + ec + " send job " + job + " received " + o); } } catch (IOException e) { logger.info("receive exception " + myId + " send job " + job + ", " + e); // e.printStackTrace(); running = false; } catch (ClassNotFoundException e) { logger.info("receive exception " + myId + " send job " + job + ", " + e); // e.printStackTrace(); running = false; } finally { logger.info( "receive finally " + myId + " at " + ec + " send job " + job + " received " + o + " running " + running); } working = false; time += System.currentTimeMillis() - t; done++; if (debug) { logger.info("done " + myId + " with " + o); } } catch (InterruptedException e) { running = false; Thread.currentThread().interrupt(); } } logger.info("terminated " + myId + " , done " + done + " jobs in " + time + " milliseconds"); }