PageRenderTime 155ms CodeModel.GetById 151ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/bundles/plugins-trunk/CommonControls/common/threads/WorkRequest.java

#
Java | 101 lines | 54 code | 11 blank | 36 comment | 2 complexity | 18b4b72b27273f68857d1361a7eee9d4 MD5 | raw file
  1/*
  2 * WorkRequest.java - a work request in a WorkThreadPool.
  3 * Copyright (c) 2005 Marcelo Vanzin
  4 *
  5 * :tabSize=4:indentSize=4:noTabs=false:maxLineLen=0:
  6 *
  7 * This program is free software; you can redistribute it and/or
  8 * modify it under the terms of the GNU General Public License
  9 * as published by the Free Software Foundation; either version 2
 10 * of the License, or any later version.
 11 *
 12 * This program is distributed in the hope that it will be useful,
 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 15 * GNU General Public License for more details.
 16 *
 17 * You should have received a copy of the GNU General Public License
 18 * along with this program; if not, write to the Free Software
 19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 20 */
 21package common.threads;
 22
 23import org.gjt.sp.util.Log;
 24
 25/**
 26 *	<p>A work request to the thread pool. Allow other threads to wait until
 27 *	the "runnable" is finished. This is basically a concurrent.Future implementation.
 28 *
 29 *  @see java.util.concurrent.Future
 30 *  @see org.gjt.sp.util.Task
 31 *  @see org.gjt.sp.util.ThreadUtilities
 32 *	@author		Marcelo Vanzin
 33 *	@since		CC 0.9.0
 34 */
 35 
 36public final class WorkRequest
 37{
 38
 39	private volatile boolean done;
 40	private Object		lock;
 41	private Runnable	work;
 42	private Exception	error;
 43
 44	public WorkRequest(Runnable work)
 45	{
 46		this.done = false;
 47		this.lock = new Object();
 48		this.work = work;
 49	}
 50
 51	/** Waits until the running job is finished. */
 52	public void waitFor() throws InterruptedException
 53	{
 54		if (done)
 55			return;
 56		synchronized (lock)
 57		{
 58			while (!done) {
 59				lock.wait(1000);
 60			}
 61		}
 62	}
 63
 64	public boolean isDone() {
 65		synchronized (lock)
 66		{
 67			return done;
 68		}
 69	}
 70
 71	/**
 72	 * Returns any exception that was caught while running the request.
 73	 *
 74	 * @since CC 0.9.4
 75	 */
 76	public Exception getError()
 77	{
 78		return error;
 79	}
 80
 81	protected void run()
 82	{
 83		try {
 84			work.run();
 85		} catch (Exception e) {
 86			Log.log(Log.ERROR, this, e);
 87			error = e;
 88		}
 89		synchronized (lock)
 90		{
 91			done = true;
 92			lock.notifyAll();
 93		}
 94	}
 95
 96	protected Runnable getRunnable()
 97	{
 98		return work;
 99	}
100
101}