harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ndbe...@apache.org
Subject svn commit: r421111 [4/11] - in /incubator/harmony/enhanced/classlib/trunk/sandbox: ./ juc-proposal/ juc-proposal/concurrent/ juc-proposal/concurrent/.settings/ juc-proposal/concurrent/META-INF/ juc-proposal/concurrent/src/ juc-proposal/concurrent/src/...
Date Wed, 12 Jul 2006 04:12:08 GMT
Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Delayed.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Delayed.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Delayed.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Delayed.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,32 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+import java.util.*;
+
+/**
+ * A mix-in style interface for marking objects that should be
+ * acted upon after a given delay.
+ *
+ * <p>An implementation of this interface must define a
+ * <tt>compareTo</tt> method that provides an ordering consistent with
+ * its <tt>getDelay</tt> method.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+public interface Delayed extends Comparable {
+
+    /**
+     * Returns the delay associated with this object, in the given time unit.
+     *
+     * @param unit the time unit
+     * @return the delay; zero or negative values indicate that the
+     * delay has already elapsed
+     */
+    long getDelay(TimeUnit unit);
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Delayed.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Exchanger.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Exchanger.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Exchanger.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Exchanger.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,247 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+import java.util.concurrent.locks.*;
+
+/**
+ * A synchronization point at which two threads can exchange objects.
+ * Each thread presents some object on entry to the {@link #exchange
+ * exchange} method, and receives the object presented by the other
+ * thread on return.
+ *
+ * <p><b>Sample Usage:</b>
+ * Here are the highlights of a class that uses an <tt>Exchanger</tt> to
+ * swap buffers between threads so that the thread filling the
+ * buffer gets a freshly
+ * emptied one when it needs it, handing off the filled one to
+ * the thread emptying the buffer.
+ * <pre>
+ * class FillAndEmpty {
+ *   Exchanger&lt;DataBuffer&gt; exchanger = new Exchanger();
+ *   DataBuffer initialEmptyBuffer = ... a made-up type
+ *   DataBuffer initialFullBuffer = ...
+ *
+ *   class FillingLoop implements Runnable {
+ *     public void run() {
+ *       DataBuffer currentBuffer = initialEmptyBuffer;
+ *       try {
+ *         while (currentBuffer != null) {
+ *           addToBuffer(currentBuffer);
+ *           if (currentBuffer.full())
+ *             currentBuffer = exchanger.exchange(currentBuffer);
+ *         }
+ *       } catch (InterruptedException ex) { ... handle ... }
+ *     }
+ *   }
+ *
+ *   class EmptyingLoop implements Runnable {
+ *     public void run() {
+ *       DataBuffer currentBuffer = initialFullBuffer;
+ *       try {
+ *         while (currentBuffer != null) {
+ *           takeFromBuffer(currentBuffer);
+ *           if (currentBuffer.empty())
+ *             currentBuffer = exchanger.exchange(currentBuffer);
+ *         }
+ *       } catch (InterruptedException ex) { ... handle ...}
+ *     }
+ *   }
+ *
+ *   void start() {
+ *     new Thread(new FillingLoop()).start();
+ *     new Thread(new EmptyingLoop()).start();
+ *   }
+ * }
+ * </pre>
+ *
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> The type of objects that may be exchanged
+ */
+public class Exchanger<V> {
+    private final ReentrantLock lock = new ReentrantLock();
+    private final Condition taken = lock.newCondition();
+
+    /** Holder for the item being exchanged */
+    private V item;
+    
+    /**
+     * Arrival count transitions from 0 to 1 to 2 then back to 0
+     * during an exchange.
+     */
+    private int arrivalCount;
+
+    /**
+     * Main exchange function, handling the different policy variants.
+     */
+    private V doExchange(V x, boolean timed, long nanos) throws InterruptedException, TimeoutException {
+        lock.lock();
+        try {
+            V other;
+
+            // If arrival count already at two, we must wait for
+            // a previous pair to finish and reset the count;
+            while (arrivalCount == 2) {
+                if (!timed)
+                    taken.await();
+                else if (nanos > 0) 
+                    nanos = taken.awaitNanos(nanos);
+                else 
+                    throw new TimeoutException();
+            }
+
+            int count = ++arrivalCount;
+
+            // If item is already waiting, replace it and signal other thread
+            if (count == 2) { 
+                other = item;
+                item = x;
+                taken.signal();
+                return other;
+            }
+
+            // Otherwise, set item and wait for another thread to
+            // replace it and signal us.
+
+            item = x;
+            InterruptedException interrupted = null;
+            try { 
+                while (arrivalCount != 2) {
+                    if (!timed)
+                        taken.await();
+                    else if (nanos > 0) 
+                        nanos = taken.awaitNanos(nanos);
+                    else 
+                        break; // timed out
+                }
+            } catch (InterruptedException ie) {
+                interrupted = ie;
+            }
+
+            // Get and reset item and count after the wait.
+            // (We need to do this even if wait was aborted.)
+            other = item;
+            item = null;
+            count = arrivalCount;
+            arrivalCount = 0; 
+            taken.signal();
+            
+            // If the other thread replaced item, then we must
+            // continue even if cancelled.
+            if (count == 2) {
+                if (interrupted != null)
+                    Thread.currentThread().interrupt();
+                return other;
+            }
+
+            // If no one is waiting for us, we can back out
+            if (interrupted != null) 
+                throw interrupted;
+            else  // must be timeout
+                throw new TimeoutException();
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Create a new Exchanger.
+     **/
+    public Exchanger() {
+    }
+
+    /**
+     * Waits for another thread to arrive at this exchange point (unless
+     * it is {@link Thread#interrupt interrupted}),
+     * and then transfers the given object to it, receiving its object
+     * in return.
+     * <p>If another thread is already waiting at the exchange point then
+     * it is resumed for thread scheduling purposes and receives the object
+     * passed in by the current thread. The current thread returns immediately,
+     * receiving the object passed to the exchange by that other thread.
+     * <p>If no other thread is already waiting at the exchange then the 
+     * current thread is disabled for thread scheduling purposes and lies
+     * dormant until one of two things happens:
+     * <ul>
+     * <li>Some other thread enters the exchange; or
+     * <li>Some other thread {@link Thread#interrupt interrupts} the current
+     * thread.
+     * </ul>
+     * <p>If the current thread:
+     * <ul>
+     * <li>has its interrupted status set on entry to this method; or 
+     * <li>is {@link Thread#interrupt interrupted} while waiting
+     * for the exchange, 
+     * </ul>
+     * then {@link InterruptedException} is thrown and the current thread's 
+     * interrupted status is cleared. 
+     *
+     * @param x the object to exchange
+     * @return the object provided by the other thread.
+     * @throws InterruptedException if current thread was interrupted 
+     * while waiting
+     **/
+    public V exchange(V x) throws InterruptedException {
+        try {
+            return doExchange(x, false, 0);
+        } catch (TimeoutException cannotHappen) { 
+            throw new Error(cannotHappen);
+        }
+    }
+
+    /**
+     * Waits for another thread to arrive at this exchange point (unless
+     * it is {@link Thread#interrupt interrupted}, or the specified waiting
+     * time elapses),
+     * and then transfers the given object to it, receiving its object
+     * in return.
+     *
+     * <p>If another thread is already waiting at the exchange point then
+     * it is resumed for thread scheduling purposes and receives the object
+     * passed in by the current thread. The current thread returns immediately,
+     * receiving the object passed to the exchange by that other thread.
+     *
+     * <p>If no other thread is already waiting at the exchange then the 
+     * current thread is disabled for thread scheduling purposes and lies
+     * dormant until one of three things happens:
+     * <ul>
+     * <li>Some other thread enters the exchange; or
+     * <li>Some other thread {@link Thread#interrupt interrupts} the current
+     * thread; or
+     * <li>The specified waiting time elapses.
+     * </ul>
+     * <p>If the current thread:
+     * <ul>
+     * <li>has its interrupted status set on entry to this method; or 
+     * <li>is {@link Thread#interrupt interrupted} while waiting
+     * for the exchange, 
+     * </ul>
+     * then {@link InterruptedException} is thrown and the current thread's 
+     * interrupted status is cleared. 
+     *
+     * <p>If the specified waiting time elapses then {@link TimeoutException}
+     * is thrown.
+     * If the time is 
+     * less than or equal to zero, the method will not wait at all.
+     *
+     * @param x the object to exchange
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the <tt>timeout</tt> argument.
+     * @return the object provided by the other thread.
+     * @throws InterruptedException if current thread was interrupted
+     * while waiting
+     * @throws TimeoutException if the specified waiting time elapses before
+     * another thread enters the exchange.
+     **/
+    public V exchange(V x, long timeout, TimeUnit unit) 
+        throws InterruptedException, TimeoutException {
+        return doExchange(x, true, unit.toNanos(timeout));
+    }
+
+}
+
+

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Exchanger.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutionException.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutionException.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutionException.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutionException.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,65 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+/**
+ * Exception thrown when attempting to retrieve the result of a task
+ * that aborted by throwing an exception. This exception can be
+ * inspected using the {@link #getCause()} method.
+ *
+ * @see Future
+ * @since 1.5
+ * @author Doug Lea
+ */
+public class ExecutionException extends Exception {
+    private static final long serialVersionUID = 7830266012832686185L;
+
+    /**
+     * Constructs a <tt>ExecutionException</tt> with no detail message.
+     * The cause is not initialized, and may subsequently be
+     * initialized by a call to {@link #initCause(Throwable) initCause}.
+     */
+    protected ExecutionException() { }
+
+    /**
+     * Constructs a <tt>ExecutionException</tt> with the specified detail
+     * message. The cause is not initialized, and may subsequently be
+     * initialized by a call to {@link #initCause(Throwable) initCause}.
+     *
+     * @param message the detail message
+     */
+    protected ExecutionException(String message) {
+        super(message);
+    }
+
+    /**
+     * Constructs a <tt>ExecutionException</tt> with the specified detail
+     * message and cause.
+     *
+     * @param  message the detail message
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method)
+     */
+    public ExecutionException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    /**
+     * Constructs a <tt>ExecutionException</tt> with the specified cause.
+     * The detail message is set to:
+     * <pre>
+     *  (cause == null ? null : cause.toString())</pre>
+     * (which typically contains the class and detail message of
+     * <tt>cause</tt>).
+     *
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method)
+     */
+    public ExecutionException(Throwable cause) {
+        super(cause);
+    }
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutionException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executor.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executor.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executor.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executor.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,107 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+/**
+ * An object that executes submitted {@link Runnable} tasks. This
+ * interface provides a way of decoupling task submission from the
+ * mechanics of how each task will be run, including details of thread
+ * use, scheduling, etc.  An <tt>Executor</tt> is normally used
+ * instead of explicitly creating threads. For example, rather than
+ * invoking <tt>new Thread(new(RunnableTask())).start()</tt> for each
+ * of a set of tasks, you might use:
+ *
+ * <pre>
+ * Executor executor = <em>anExecutor</em>;
+ * executor.execute(new RunnableTask1());
+ * executor.execute(new RunnableTask2());
+ * ...
+ * </pre>
+ * 
+ * However, the <tt>Executor</tt> interface does not strictly
+ * require that execution be asynchronous. In the simplest case, an
+ * executor can run the submitted task immediately in the caller's
+ * thread:
+ *
+ * <pre>
+ * class DirectExecutor implements Executor {
+ *     public void execute(Runnable r) {
+ *         r.run();
+ *     }
+ * }</pre>
+ *
+ * More typically, tasks are executed in some thread other
+ * than the caller's thread.  The executor below spawns a new thread
+ * for each task.
+ *
+ * <pre>
+ * class ThreadPerTaskExecutor implements Executor {
+ *     public void execute(Runnable r) {
+ *         new Thread(r).start();
+ *     }
+ * }</pre>
+ *
+ * Many <tt>Executor</tt> implementations impose some sort of
+ * limitation on how and when tasks are scheduled.  The executor below
+ * serializes the submission of tasks to a second executor,
+ * illustrating a composite executor.
+ *
+ * <pre>
+ * class SerialExecutor implements Executor {
+ *     final Queue&lt;Runnable&gt; tasks = new LinkedBlockingQueue&lt;Runnable&gt;();
+ *     final Executor executor;
+ *     Runnable active;
+ *
+ *     SerialExecutor(Executor executor) {
+ *         this.executor = executor;
+ *     }
+ *
+ *     public synchronized void execute(final Runnable r) {
+ *         tasks.offer(new Runnable() {
+ *             public void run() {
+ *                 try {
+ *                     r.run();
+ *                 } finally {
+ *                     scheduleNext();
+ *                 }
+ *             }
+ *         });
+ *         if (active == null) {
+ *             scheduleNext();
+ *         }
+ *     }
+ *
+ *     protected synchronized void scheduleNext() {
+ *         if ((active = tasks.poll()) != null) {
+ *             executor.execute(active);
+ *         }
+ *     }
+ * }</pre>
+ *
+ * The <tt>Executor</tt> implementations provided in this package
+ * implement {@link ExecutorService}, which is a more extensive
+ * interface.  The {@link ThreadPoolExecutor} class provides an
+ * extensible thread pool implementation. The {@link Executors} class
+ * provides convenient factory methods for these Executors.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+public interface Executor {
+
+    /**
+     * Executes the given command at some time in the future.  The command
+     * may execute in a new thread, in a pooled thread, or in the calling
+     * thread, at the discretion of the <tt>Executor</tt> implementation.
+     *
+     * @param command the runnable task
+     * @throws RejectedExecutionException if this task cannot be
+     * accepted for execution.
+     * @throws NullPointerException if command is null
+     */
+    void execute(Runnable command);
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorCompletionService.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorCompletionService.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorCompletionService.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorCompletionService.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,148 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+
+/**
+ * A {@link CompletionService} that uses a supplied {@link Executor}
+ * to execute tasks.  This class arranges that submitted tasks are,
+ * upon completion, placed on a queue accessible using <tt>take</tt>.
+ * The class is lightweight enough to be suitable for transient use
+ * when processing groups of tasks.
+ *
+ * <p>
+ *
+ * <b>Usage Examples.</b>
+ *
+ * Suppose you have a set of solvers for a certain problem, each
+ * returning a value of some type <tt>Result</tt>, and would like to
+ * run them concurrently, processing the results of each of them that
+ * return a non-null value, in some method <tt>use(Result r)</tt>. You
+ * could write this as:
+ *
+ * <pre>
+ *    void solve(Executor e, Collection&lt;Callable&lt;Result&gt;&gt; solvers)
+ *      throws InterruptedException, ExecutionException {
+ *        CompletionService&lt;Result&gt; ecs = new ExecutorCompletionService&lt;Result&gt;(e);
+ *        for (Callable&lt;Result&gt; s : solvers)
+ *            ecs.submit(s);
+ *        int n = solvers.size();
+ *        for (int i = 0; i &lt; n; ++i) {
+ *            Result r = ecs.take().get();
+ *            if (r != null) 
+ *                use(r);
+ *        }
+ *    }
+ * </pre>
+ *
+ * Suppose instead that you would like to use the first non-null result
+ * of the set of tasks, ignoring any that encounter exceptions,
+ * and cancelling all other tasks when the first one is ready:
+ *
+ * <pre>
+ *    void solve(Executor e, Collection&lt;Callable&lt;Result&gt;&gt; solvers) 
+ *      throws InterruptedException {
+ *        CompletionService&lt;Result&gt; ecs = new ExecutorCompletionService&lt;Result&gt;(e);
+ *        int n = solvers.size();
+ *        List&lt;Future&lt;Result&gt;&gt; futures = new ArrayList&lt;Future&lt;Result&gt;&gt;(n);
+ *        Result result = null;
+ *        try {
+ *            for (Callable&lt;Result&gt; s : solvers)
+ *                futures.add(ecs.submit(s));
+ *            for (int i = 0; i &lt; n; ++i) {
+ *                try {
+ *                    Result r = ecs.take().get();
+ *                    if (r != null) {
+ *                        result = r;
+ *                        break;
+ *                    }
+ *                } catch(ExecutionException ignore) {}
+ *            }
+ *        }
+ *        finally {
+ *            for (Future&lt;Result&gt; f : futures)
+ *                f.cancel(true);
+ *        }
+ *
+ *        if (result != null)
+ *            use(result);
+ *    }
+ * </pre>
+ */
+public class ExecutorCompletionService<V> implements CompletionService<V> {
+    private final Executor executor;
+    private final BlockingQueue<Future<V>> completionQueue;
+
+    /**
+     * FutureTask extension to enqueue upon completion
+     */
+    private class QueueingFuture extends FutureTask<V> {
+        QueueingFuture(Callable<V> c) { super(c); }
+        QueueingFuture(Runnable t, V r) { super(t, r); }
+        protected void done() { completionQueue.add(this); }
+    }
+
+    /**
+     * Creates an ExecutorCompletionService using the supplied
+     * executor for base task execution and a
+     * {@link LinkedBlockingQueue} as a completion queue.
+     * @param executor the executor to use
+     * @throws NullPointerException if executor is <tt>null</tt>
+     */
+    public ExecutorCompletionService(Executor executor) {
+        if (executor == null) 
+            throw new NullPointerException();
+        this.executor = executor;
+        this.completionQueue = new LinkedBlockingQueue<Future<V>>();
+    }
+
+    /**
+     * Creates an ExecutorCompletionService using the supplied
+     * executor for base task execution and the supplied queue as its
+     * completion queue.
+     * @param executor the executor to use
+     * @param completionQueue the queue to use as the completion queue
+     * normally one dedicated for use by this service
+     * @throws NullPointerException if executor or completionQueue are <tt>null</tt>
+     */
+    public ExecutorCompletionService(Executor executor,
+                                     BlockingQueue<Future<V>> completionQueue) {
+        if (executor == null || completionQueue == null) 
+            throw new NullPointerException();
+        this.executor = executor;
+        this.completionQueue = completionQueue;
+    }
+
+    public Future<V> submit(Callable<V> task) {
+        if (task == null) throw new NullPointerException();
+        QueueingFuture f = new QueueingFuture(task);
+        executor.execute(f);
+        return f;
+    }
+
+    public Future<V> submit(Runnable task, V result) {
+        if (task == null) throw new NullPointerException();
+        QueueingFuture f = new QueueingFuture(task, result);
+        executor.execute(f);
+        return f;
+    }
+
+    public Future<V> take() throws InterruptedException {
+        return completionQueue.take();
+    }
+
+    public Future<V> poll() {
+        return completionQueue.poll();
+    }
+
+    public Future<V> poll(long timeout, TimeUnit unit) throws InterruptedException {
+        return completionQueue.poll(timeout, unit);
+    }
+
+}
+
+

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorCompletionService.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorService.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorService.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorService.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorService.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,286 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+import java.util.List;
+import java.util.Collection;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * An {@link Executor} that provides methods to manage termination and
+ * methods that can produce a {@link Future} for tracking progress of
+ * one or more asynchronous tasks.  
+ *
+ * <p>
+ * An <tt>ExecutorService</tt> can be shut down, which will cause it
+ * to stop accepting new tasks.  After being shut down, the executor
+ * will eventually terminate, at which point no tasks are actively
+ * executing, no tasks are awaiting execution, and no new tasks can be
+ * submitted.
+ *
+ * <p> Method <tt>submit</tt> extends base method {@link
+ * Executor#execute} by creating and returning a {@link Future} that
+ * can be used to cancel execution and/or wait for completion.
+ * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
+ * commonly useful forms of bulk execution, executing a collection of
+ * tasks and then waiting for at least one, or all, to
+ * complete. (Class {@link ExecutorCompletionService} can be used to
+ * write customized variants of these methods.)
+ *
+ * <p>The {@link Executors} class provides factory methods for the
+ * executor services provided in this package.
+ *
+ * <h3>Usage Example</h3>
+ *
+ * Here is a sketch of a network service in which threads in a thread
+ * pool service incoming requests. It uses the preconfigured {@link
+ * Executors#newFixedThreadPool} factory method:
+ *
+ * <pre>
+ * class NetworkService {
+ *    private final ServerSocket serverSocket;
+ *    private final ExecutorService pool;
+ *
+ *    public NetworkService(int port, int poolSize) throws IOException {
+ *      serverSocket = new ServerSocket(port);
+ *      pool = Executors.newFixedThreadPool(poolSize);
+ *    }
+ * 
+ *    public void serve() {
+ *      try {
+ *        for (;;) {
+ *          pool.execute(new Handler(serverSocket.accept()));
+ *        }
+ *      } catch (IOException ex) {
+ *        pool.shutdown();
+ *      }
+ *    }
+ *  }
+ *
+ *  class Handler implements Runnable {
+ *    private final Socket socket;
+ *    Handler(Socket socket) { this.socket = socket; }
+ *    public void run() {
+ *      // read and service request
+ *    }
+ * }
+ * </pre>
+ * @since 1.5
+ * @author Doug Lea
+ */
+public interface ExecutorService extends Executor {
+
+    /**
+     * Initiates an orderly shutdown in which previously submitted
+     * tasks are executed, but no new tasks will be
+     * accepted. Invocation has no additional effect if already shut
+     * down.
+     * @throws SecurityException if a security manager exists and
+     * shutting down this ExecutorService may manipulate threads that
+     * the caller is not permitted to modify because it does not hold
+     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
+     * or the security manager's <tt>checkAccess</tt>  method denies access.
+     */
+    void shutdown();
+
+    /**
+     * Attempts to stop all actively executing tasks, halts the
+     * processing of waiting tasks, and returns a list of the tasks that were
+     * awaiting execution. 
+     *  
+     * <p>There are no guarantees beyond best-effort attempts to stop
+     * processing actively executing tasks.  For example, typical
+     * implementations will cancel via {@link Thread#interrupt}, so if any
+     * tasks mask or fail to respond to interrupts, they may never terminate.
+     *
+     * @return list of tasks that never commenced execution
+     * @throws SecurityException if a security manager exists and
+     * shutting down this ExecutorService may manipulate threads that
+     * the caller is not permitted to modify because it does not hold
+     * {@link java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
+     * or the security manager's <tt>checkAccess</tt> method denies access.
+     */
+    List<Runnable> shutdownNow();
+
+    /**
+     * Returns <tt>true</tt> if this executor has been shut down.
+     *
+     * @return <tt>true</tt> if this executor has been shut down
+     */
+    boolean isShutdown();
+
+    /**
+     * Returns <tt>true</tt> if all tasks have completed following shut down.
+     * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
+     * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
+     *
+     * @return <tt>true</tt> if all tasks have completed following shut down
+     */
+    boolean isTerminated();
+
+    /**
+     * Blocks until all tasks have completed execution after a shutdown
+     * request, or the timeout occurs, or the current thread is
+     * interrupted, whichever happens first.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return <tt>true</tt> if this executor terminated and <tt>false</tt>
+     * if the timeout elapsed before termination
+     * @throws InterruptedException if interrupted while waiting
+     */
+    boolean awaitTermination(long timeout, TimeUnit unit)
+        throws InterruptedException;
+
+
+    /**
+     * Submits a value-returning task for execution and returns a Future
+     * representing the pending results of the task. 
+     *
+     * <p>
+     * If you would like to immediately block waiting
+     * for a task, you can use constructions of the form
+     * <tt>result = exec.submit(aCallable).get();</tt>
+     *
+     * <p> Note: The {@link Executors} class includes a set of methods
+     * that can convert some other common closure-like objects,
+     * for example, {@link java.security.PrivilegedAction} to
+     * {@link Callable} form so they can be submitted.
+     *
+     * @param task the task to submit
+     * @return a Future representing pending completion of the task
+     * @throws RejectedExecutionException if task cannot be scheduled
+     * for execution
+     * @throws NullPointerException if task null
+     */
+    <T> Future<T> submit(Callable<T> task);
+
+    /**
+     * Submits a Runnable task for execution and returns a Future 
+     * representing that task that will upon completion return 
+     * the given result
+     *
+     * @param task the task to submit
+     * @param result the result to return
+     * @return a Future representing pending completion of the task,
+     * and whose <tt>get()</tt> method will return the given result
+     * upon completion.
+     * @throws RejectedExecutionException if task cannot be scheduled
+     * for execution
+     * @throws NullPointerException if task null     
+     */
+    <T> Future<T> submit(Runnable task, T result);
+
+    /**
+     * Submits a Runnable task for execution and returns a Future 
+     * representing that task.
+     *
+     * @param task the task to submit
+     * @return a Future representing pending completion of the task,
+     * and whose <tt>get()</tt> method will return <tt>null</tt>
+     * upon completion.
+     * @throws RejectedExecutionException if task cannot be scheduled
+     * for execution
+     * @throws NullPointerException if task null
+     */
+    Future<?> submit(Runnable task);
+
+    /**
+     * Executes the given tasks, returning their results
+     * when all complete.
+     * Note that a <em>completed</em> task could have
+     * terminated either normally or by throwing an exception.
+     * The results of this method are undefined if the given
+     * collection is modified while this operation is in progress.
+     * @param tasks the collection of tasks
+     * @return A list of Futures representing the tasks, in the same
+     * sequential order as produced by the iterator for the given task
+     * list, each of which has completed.
+     * @throws InterruptedException if interrupted while waiting, in
+     * which case unfinished tasks are cancelled.
+     * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
+     * @throws RejectedExecutionException if any task cannot be scheduled
+     * for execution
+     */
+
+    <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
+        throws InterruptedException;
+
+    /**
+     * Executes the given tasks, returning their results
+     * when all complete or the timeout expires, whichever happens first.
+     * Upon return, tasks that have not completed are cancelled.
+     * Note that a <em>completed</em> task could have
+     * terminated either normally or by throwing an exception.
+     * The results of this method are undefined if the given
+     * collection is modified while this operation is in progress.
+     * @param tasks the collection of tasks
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return A list of Futures representing the tasks, in the same
+     * sequential order as produced by the iterator for the given
+     * task list. If the operation did not time out, each task will
+     * have completed. If it did time out, some of thiese tasks will
+     * not have completed.
+     * @throws InterruptedException if interrupted while waiting, in
+     * which case unfinished tasks are cancelled.
+     * @throws NullPointerException if tasks, any of its elements, or
+     * unit are <tt>null</tt>
+     * @throws RejectedExecutionException if any task cannot be scheduled
+     * for execution
+     */
+    <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, 
+                                  long timeout, TimeUnit unit) 
+        throws InterruptedException;
+
+    /**
+     * Executes the given tasks, returning the result
+     * of one that has completed successfully (i.e., without throwing
+     * an exception), if any do. Upon normal or exceptional return,
+     * tasks that have not completed are cancelled.
+     * The results of this method are undefined if the given
+     * collection is modified while this operation is in progress.
+     * @param tasks the collection of tasks
+     * @return The result returned by one of the tasks.
+     * @throws InterruptedException if interrupted while waiting
+     * @throws NullPointerException if tasks or any of its elements
+     * are <tt>null</tt>
+     * @throws IllegalArgumentException if tasks empty
+     * @throws ExecutionException if no task successfully completes
+     * @throws RejectedExecutionException if tasks cannot be scheduled
+     * for execution
+     */
+    <T> T invokeAny(Collection<Callable<T>> tasks)
+        throws InterruptedException, ExecutionException;
+
+    /**
+     * Executes the given tasks, returning the result
+     * of one that has completed successfully (i.e., without throwing
+     * an exception), if any do before the given timeout elapses.
+     * Upon normal or exceptional return, tasks that have not
+     * completed are cancelled.
+     * The results of this method are undefined if the given
+     * collection is modified while this operation is in progress.
+     * @param tasks the collection of tasks
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return The result returned by one of the tasks.
+     * @throws InterruptedException if interrupted while waiting
+     * @throws NullPointerException if tasks, any of its elements, or
+     * unit are <tt>null</tt>
+     * @throws TimeoutException if the given timeout elapses before
+     * any task successfully completes
+     * @throws ExecutionException if no task successfully completes
+     * @throws RejectedExecutionException if tasks cannot be scheduled
+     * for execution
+     */
+    <T> T invokeAny(Collection<Callable<T>> tasks, 
+                    long timeout, TimeUnit unit) 
+        throws InterruptedException, ExecutionException, TimeoutException;
+
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/ExecutorService.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executors.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executors.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executors.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executors.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,659 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedExceptionAction;
+import java.security.AccessControlException;
+
+/**
+ * Factory and utility methods for {@link Executor}, {@link
+ * ExecutorService}, {@link ScheduledExecutorService}, {@link
+ * ThreadFactory}, and {@link Callable} classes defined in this
+ * package. This class supports the following kinds of methods:
+ * 
+ * <ul>
+ *   <li> Methods that create and return an {@link ExecutorService} 
+ *        set up with commonly useful configuration settings. 
+ *   <li> Methods that create and return a {@link ScheduledExecutorService} 
+ *        set up with commonly useful configuration settings. 
+ *   <li> Methods that create and return a "wrapped" ExecutorService, that
+ *        disables reconfiguration by making implementation-specific methods
+ *        inaccessible.
+ *   <li> Methods that create and return a {@link ThreadFactory}
+ *        that sets newly created threads to a known state.
+ *   <li> Methods that create and return a {@link Callable} 
+ *        out of other closure-like forms, so they can be used
+ *        in execution methods requiring <tt>Callable</tt>.
+ * </ul>
+ *
+ * @since 1.5
+ * @author Doug Lea
+ */
+public class Executors {
+
+    /**
+     * Creates a thread pool that reuses a fixed set of threads
+     * operating off a shared unbounded queue. If any thread
+     * terminates due to a failure during execution prior to shutdown,
+     * a new one will take its place if needed to execute subsequent
+     * tasks.
+     *
+     * @param nThreads the number of threads in the pool
+     * @return the newly created thread pool
+     */
+    public static ExecutorService newFixedThreadPool(int nThreads) {
+        return new ThreadPoolExecutor(nThreads, nThreads,
+                                      0L, TimeUnit.MILLISECONDS,
+                                      new LinkedBlockingQueue<Runnable>());
+    }
+
+    /**
+     * Creates a thread pool that reuses a fixed set of threads
+     * operating off a shared unbounded queue, using the provided
+     * ThreadFactory to create new threads when needed.
+     *
+     * @param nThreads the number of threads in the pool
+     * @param threadFactory the factory to use when creating new threads
+     * @return the newly created thread pool
+     */
+    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
+        return new ThreadPoolExecutor(nThreads, nThreads,
+                                      0L, TimeUnit.MILLISECONDS,
+                                      new LinkedBlockingQueue<Runnable>(),
+                                      threadFactory);
+    }
+
+    /**
+     * Creates an Executor that uses a single worker thread operating
+     * off an unbounded queue. (Note however that if this single
+     * thread terminates due to a failure during execution prior to
+     * shutdown, a new one will take its place if needed to execute
+     * subsequent tasks.)  Tasks are guaranteed to execute
+     * sequentially, and no more than one task will be active at any
+     * given time. Unlike the otherwise equivalent
+     * <tt>newFixedThreadPool(1)</tt> the returned executor is
+     * guaranteed not to be reconfigurable to use additional threads.
+     *
+     * @return the newly created single-threaded Executor
+     */
+    public static ExecutorService newSingleThreadExecutor() {
+        return new DelegatedExecutorService
+            (new ThreadPoolExecutor(1, 1,
+                                    0L, TimeUnit.MILLISECONDS,
+                                    new LinkedBlockingQueue<Runnable>()));
+    }
+
+    /**
+     * Creates an Executor that uses a single worker thread operating
+     * off an unbounded queue, and uses the provided ThreadFactory to
+     * create a new thread when needed. Unlike the otherwise
+     * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the returned executor
+     * is guaranteed not to be reconfigurable to use additional
+     * threads.
+     * 
+     * @param threadFactory the factory to use when creating new
+     * threads
+     *
+     * @return the newly created single-threaded Executor
+     */
+    public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
+        return new DelegatedExecutorService
+            (new ThreadPoolExecutor(1, 1,
+                                    0L, TimeUnit.MILLISECONDS,
+                                    new LinkedBlockingQueue<Runnable>(),
+                                    threadFactory));
+    }
+
+    /**
+     * Creates a thread pool that creates new threads as needed, but
+     * will reuse previously constructed threads when they are
+     * available.  These pools will typically improve the performance
+     * of programs that execute many short-lived asynchronous tasks.
+     * Calls to <tt>execute</tt> will reuse previously constructed
+     * threads if available. If no existing thread is available, a new
+     * thread will be created and added to the pool. Threads that have
+     * not been used for sixty seconds are terminated and removed from
+     * the cache. Thus, a pool that remains idle for long enough will
+     * not consume any resources. Note that pools with similar
+     * properties but different details (for example, timeout parameters)
+     * may be created using {@link ThreadPoolExecutor} constructors.
+     *
+     * @return the newly created thread pool
+     */
+    public static ExecutorService newCachedThreadPool() {
+        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
+                                      60L, TimeUnit.SECONDS,
+                                      new SynchronousQueue<Runnable>());
+    }
+
+    /**
+     * Creates a thread pool that creates new threads as needed, but
+     * will reuse previously constructed threads when they are
+     * available, and uses the provided
+     * ThreadFactory to create new threads when needed.
+     * @param threadFactory the factory to use when creating new threads
+     * @return the newly created thread pool
+     */
+    public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
+        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
+                                      60L, TimeUnit.SECONDS,
+                                      new SynchronousQueue<Runnable>(),
+                                      threadFactory);
+    }
+   
+    /**
+     * Creates a single-threaded executor that can schedule commands
+     * to run after a given delay, or to execute periodically.
+     * (Note however that if this single
+     * thread terminates due to a failure during execution prior to
+     * shutdown, a new one will take its place if needed to execute
+     * subsequent tasks.)  Tasks are guaranteed to execute
+     * sequentially, and no more than one task will be active at any
+     * given time. Unlike the otherwise equivalent
+     * <tt>newScheduledThreadPool(1)</tt> the returned executor is
+     * guaranteed not to be reconfigurable to use additional threads.
+     * @return the newly created scheduled executor
+     */
+    public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
+        return new DelegatedScheduledExecutorService
+            (new ScheduledThreadPoolExecutor(1));
+    }
+
+    /**
+     * Creates a single-threaded executor that can schedule commands
+     * to run after a given delay, or to execute periodically.  (Note
+     * however that if this single thread terminates due to a failure
+     * during execution prior to shutdown, a new one will take its
+     * place if needed to execute subsequent tasks.)  Tasks are
+     * guaranteed to execute sequentially, and no more than one task
+     * will be active at any given time. Unlike the otherwise
+     * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
+     * the returned executor is guaranteed not to be reconfigurable to
+     * use additional threads.
+     * @param threadFactory the factory to use when creating new
+     * threads
+     * @return a newly created scheduled executor
+     */
+    public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {
+        return new DelegatedScheduledExecutorService
+            (new ScheduledThreadPoolExecutor(1, threadFactory));
+    }
+    
+    /**
+     * Creates a thread pool that can schedule commands to run after a 
+     * given delay, or to execute periodically.
+     * @param corePoolSize the number of threads to keep in the pool,
+     * even if they are idle.
+     * @return a newly created scheduled thread pool
+     */
+    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
+        return new ScheduledThreadPoolExecutor(corePoolSize);
+    }
+
+    /**
+     * Creates a thread pool that can schedule commands to run after a 
+     * given delay, or to execute periodically.
+     * @param corePoolSize the number of threads to keep in the pool,
+     * even if they are idle.
+     * @param threadFactory the factory to use when the executor
+     * creates a new thread. 
+     * @return a newly created scheduled thread pool
+     */
+    public static ScheduledExecutorService newScheduledThreadPool(
+            int corePoolSize, ThreadFactory threadFactory) {
+        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
+    }
+
+
+    /**
+     * Returns an object that delegates all defined {@link
+     * ExecutorService} methods to the given executor, but not any
+     * other methods that might otherwise be accessible using
+     * casts. This provides a way to safely "freeze" configuration and
+     * disallow tuning of a given concrete implementation.
+     * @param executor the underlying implementation
+     * @return an <tt>ExecutorService</tt> instance
+     * @throws NullPointerException if executor null
+     */
+    public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
+        if (executor == null)
+            throw new NullPointerException();
+        return new DelegatedExecutorService(executor);
+    }
+
+    /**
+     * Returns an object that delegates all defined {@link
+     * ScheduledExecutorService} methods to the given executor, but
+     * not any other methods that might otherwise be accessible using
+     * casts. This provides a way to safely "freeze" configuration and
+     * disallow tuning of a given concrete implementation.
+     * @param executor the underlying implementation
+     * @return a <tt>ScheduledExecutorService</tt> instance
+     * @throws NullPointerException if executor null
+     */
+    public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
+        if (executor == null)
+            throw new NullPointerException();
+        return new DelegatedScheduledExecutorService(executor);
+    }
+        
+    /**
+     * Returns a default thread factory used to create new threads.
+     * This factory creates all new threads used by an Executor in the
+     * same {@link ThreadGroup}. If there is a {@link
+     * java.lang.SecurityManager}, it uses the group of {@link
+     * System#getSecurityManager}, else the group of the thread
+     * invoking this <tt>defaultThreadFactory</tt> method. Each new
+     * thread is created as a non-daemon thread with priority
+     * <tt>Thread.NORM_PRIORITY</tt>. New threads have names
+     * accessible via {@link Thread#getName} of
+     * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
+     * number of this factory, and <em>M</em> is the sequence number
+     * of the thread created by this factory.
+     * @return a thread factory
+     */
+    public static ThreadFactory defaultThreadFactory() {
+        return new DefaultThreadFactory();
+    }
+
+    /**
+     * Returns a thread factory used to create new threads that
+     * have the same permissions as the current thread.
+     * This factory creates threads with the same settings as {@link
+     * Executors#defaultThreadFactory}, additionally setting the
+     * AccessControlContext and contextClassLoader of new threads to
+     * be the same as the thread invoking this
+     * <tt>privilegedThreadFactory</tt> method.  A new
+     * <tt>privilegedThreadFactory</tt> can be created within an
+     * {@link AccessController#doPrivileged} action setting the
+     * current thread's access control context to create threads with
+     * the selected permission settings holding within that action.
+     *
+     * <p> Note that while tasks running within such threads will have
+     * the same access control and class loader settings as the
+     * current thread, they need not have the same {@link
+     * java.lang.ThreadLocal} or {@link
+     * java.lang.InheritableThreadLocal} values. If necessary,
+     * particular values of thread locals can be set or reset before
+     * any task runs in {@link ThreadPoolExecutor} subclasses using
+     * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
+     * necessary to initialize worker threads to have the same
+     * InheritableThreadLocal settings as some other designated
+     * thread, you can create a custom ThreadFactory in which that
+     * thread waits for and services requests to create others that
+     * will inherit its values.
+     *
+     * @return a thread factory
+     * @throws AccessControlException if the current access control
+     * context does not have permission to both get and set context
+     * class loader.
+     */
+    public static ThreadFactory privilegedThreadFactory() {
+        return new PrivilegedThreadFactory();
+    }
+
+    /**
+     * Returns a {@link Callable} object that, when
+     * called, runs the given task and returns the given result.  This
+     * can be useful when applying methods requiring a
+     * <tt>Callable</tt> to an otherwise resultless action.
+     * @param task the task to run
+     * @param result the result to return
+     * @throws NullPointerException if task null
+     * @return a callable object
+     */
+    public static <T> Callable<T> callable(Runnable task, T result) {
+        if (task == null)
+            throw new NullPointerException();
+        return new RunnableAdapter<T>(task, result);
+    }
+
+    /**
+     * Returns a {@link Callable} object that, when
+     * called, runs the given task and returns <tt>null</tt>.
+     * @param task the task to run
+     * @return a callable object
+     * @throws NullPointerException if task null
+     */
+    public static Callable<Object> callable(Runnable task) {
+        if (task == null)
+            throw new NullPointerException();
+        return new RunnableAdapter<Object>(task, null);
+    }
+
+    /**
+     * Returns a {@link Callable} object that, when
+     * called, runs the given privileged action and returns its result.
+     * @param action the privileged action to run
+     * @return a callable object
+     * @throws NullPointerException if action null
+     */
+    public static Callable<Object> callable(PrivilegedAction action) {
+        if (action == null)
+            throw new NullPointerException();
+        return new PrivilegedActionAdapter(action);
+    }
+
+    /**
+     * Returns a {@link Callable} object that, when
+     * called, runs the given privileged exception action and returns
+     * its result.
+     * @param action the privileged exception action to run
+     * @return a callable object
+     * @throws NullPointerException if action null
+     */
+    public static Callable<Object> callable(PrivilegedExceptionAction action) {
+        if (action == null)
+            throw new NullPointerException();
+        return new PrivilegedExceptionActionAdapter(action);
+    }
+
+    /**
+     * Returns a {@link Callable} object that will, when
+     * called, execute the given <tt>callable</tt> under the current
+     * access control context. This method should normally be
+     * invoked within an {@link AccessController#doPrivileged} action
+     * to create callables that will, if possible, execute under the
+     * selected permission settings holding within that action; or if
+     * not possible, throw an associated {@link
+     * AccessControlException}.
+     * @param callable the underlying task
+     * @return a callable object
+     * @throws NullPointerException if callable null
+     *
+     */
+    public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
+        if (callable == null)
+            throw new NullPointerException();
+        return new PrivilegedCallable(callable);
+    }
+    
+    /**
+     * Returns a {@link Callable} object that will, when
+     * called, execute the given <tt>callable</tt> under the current
+     * access control context, with the current context class loader
+     * as the context class loader. This method should normally be
+     * invoked within an {@link AccessController#doPrivileged} action
+     * to create callables that will, if possible, execute under the
+     * selected permission settings holding within that action; or if
+     * not possible, throw an associated {@link
+     * AccessControlException}.
+     * @param callable the underlying task
+     *
+     * @return a callable object
+     * @throws NullPointerException if callable null
+     * @throws AccessControlException if the current access control
+     * context does not have permission to both set and get context
+     * class loader.
+     */
+    public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
+        if (callable == null)
+            throw new NullPointerException();
+        return new PrivilegedCallableUsingCurrentClassLoader(callable);
+    }
+
+    // Non-public classes supporting the public methods
+
+    /**
+     * A callable that runs given task and returns given result
+     */
+    static final class RunnableAdapter<T> implements Callable<T> {
+        final Runnable task;
+        final T result;
+        RunnableAdapter(Runnable  task, T result) {
+            this.task = task; 
+            this.result = result;
+        }
+        public T call() { 
+            task.run(); 
+            return result; 
+        }
+    }
+
+    /**
+     * A callable that runs given privileged action and returns its result
+     */
+    static final class PrivilegedActionAdapter implements Callable<Object> {
+        PrivilegedActionAdapter(PrivilegedAction action) {
+            this.action = action;
+        }
+        public Object call () {
+            return action.run();
+        }
+        private final PrivilegedAction action;
+    }
+
+    /**
+     * A callable that runs given privileged exception action and returns its result
+     */
+    static final class PrivilegedExceptionActionAdapter implements Callable<Object> {
+        PrivilegedExceptionActionAdapter(PrivilegedExceptionAction action) {
+            this.action = action;
+        }
+        public Object call () throws Exception {
+            return action.run();
+        }
+        private final PrivilegedExceptionAction action;
+    }
+
+
+    /**
+     * A callable that runs under established access control settings
+     */
+    static final class PrivilegedCallable<T> implements Callable<T> {
+        private final AccessControlContext acc;
+        private final Callable<T> task;
+        private T result;
+        private Exception exception;
+        PrivilegedCallable(Callable<T> task) {
+            this.task = task;
+            this.acc = AccessController.getContext();
+        }
+
+        public T call() throws Exception {
+            AccessController.doPrivileged(new PrivilegedAction() {
+                    public Object run() {
+                        try {
+                            result = task.call();
+                        } catch(Exception ex) {
+                            exception = ex;
+                        }
+                        return null;
+                    }
+                }, acc);
+            if (exception != null)
+                throw exception;
+            else 
+                return result;
+        }
+    }
+
+    /**
+     * A callable that runs under established access control settings and
+     * current ClassLoader
+     */
+    static final class PrivilegedCallableUsingCurrentClassLoader<T> implements Callable<T> {
+        private final ClassLoader ccl;
+        private final AccessControlContext acc;
+        private final Callable<T> task;
+        private T result;
+        private Exception exception;
+        PrivilegedCallableUsingCurrentClassLoader(Callable<T> task) {
+            this.task = task;
+            this.ccl = Thread.currentThread().getContextClassLoader();
+            this.acc = AccessController.getContext();
+            acc.checkPermission(new RuntimePermission("getContextClassLoader"));
+            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
+        }
+
+        public T call() throws Exception {
+            AccessController.doPrivileged(new PrivilegedAction() {
+                    public Object run() {
+                        ClassLoader savedcl = null;
+                        Thread t = Thread.currentThread();
+                        try {
+                            ClassLoader cl = t.getContextClassLoader();
+                            if (ccl != cl) {
+                                t.setContextClassLoader(ccl);
+                                savedcl = cl;
+                            }
+                            result = task.call();
+                        } catch(Exception ex) {
+                            exception = ex;
+                        } finally {
+                            if (savedcl != null)
+                                t.setContextClassLoader(savedcl);
+                        }
+                        return null;
+                    }
+                }, acc);
+            if (exception != null)
+                throw exception;
+            else 
+                return result;
+        }
+    }
+
+    /**
+     * The default thread factory
+     */
+    static class DefaultThreadFactory implements ThreadFactory {
+        static final AtomicInteger poolNumber = new AtomicInteger(1);
+        final ThreadGroup group;
+        final AtomicInteger threadNumber = new AtomicInteger(1);
+        final String namePrefix;
+
+        DefaultThreadFactory() {
+            SecurityManager s = System.getSecurityManager();
+            group = (s != null)? s.getThreadGroup() :
+                                 Thread.currentThread().getThreadGroup();
+            namePrefix = "pool-" + 
+                          poolNumber.getAndIncrement() + 
+                         "-thread-";
+        }
+
+        public Thread newThread(Runnable r) {
+            Thread t = new Thread(group, r, 
+                                  namePrefix + threadNumber.getAndIncrement(),
+                                  0);
+            if (t.isDaemon())
+                t.setDaemon(false);
+            if (t.getPriority() != Thread.NORM_PRIORITY)
+                t.setPriority(Thread.NORM_PRIORITY);
+            return t;
+        }
+    }
+
+    /**
+     *  Thread factory capturing access control and class loader
+     */
+    static class PrivilegedThreadFactory extends DefaultThreadFactory {
+        private final ClassLoader ccl;
+        private final AccessControlContext acc;
+
+        PrivilegedThreadFactory() {
+            super();
+            this.ccl = Thread.currentThread().getContextClassLoader();
+            this.acc = AccessController.getContext();
+            acc.checkPermission(new RuntimePermission("setContextClassLoader"));
+        }
+        
+        public Thread newThread(final Runnable r) {
+            return super.newThread(new Runnable() {
+                public void run() {
+                    AccessController.doPrivileged(new PrivilegedAction() {
+                        public Object run() { 
+                            Thread.currentThread().setContextClassLoader(ccl);
+                            r.run();
+                            return null; 
+                        }
+                    }, acc);
+                }
+            });
+        }
+        
+    }
+
+   /**
+     * A wrapper class that exposes only the ExecutorService methods
+     * of an implementation.
+     */
+    static class DelegatedExecutorService extends AbstractExecutorService {
+        private final ExecutorService e;
+        DelegatedExecutorService(ExecutorService executor) { e = executor; }
+        public void execute(Runnable command) { e.execute(command); }
+        public void shutdown() { e.shutdown(); }
+        public List<Runnable> shutdownNow() { return e.shutdownNow(); }
+        public boolean isShutdown() { return e.isShutdown(); }
+        public boolean isTerminated() { return e.isTerminated(); }
+        public boolean awaitTermination(long timeout, TimeUnit unit)
+            throws InterruptedException {
+            return e.awaitTermination(timeout, unit);
+        }
+        public Future<?> submit(Runnable task) {
+            return e.submit(task);
+        }
+        public <T> Future<T> submit(Callable<T> task) {
+            return e.submit(task);
+        }
+        public <T> Future<T> submit(Runnable task, T result) {
+            return e.submit(task, result);
+        }
+        public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
+            throws InterruptedException {
+            return e.invokeAll(tasks);
+        }
+        public <T> List<Future<T>> invokeAll(Collection<Callable<T>> tasks, 
+                                             long timeout, TimeUnit unit) 
+            throws InterruptedException {
+            return e.invokeAll(tasks, timeout, unit);
+        }
+        public <T> T invokeAny(Collection<Callable<T>> tasks)
+            throws InterruptedException, ExecutionException {
+            return e.invokeAny(tasks);
+        }
+        public <T> T invokeAny(Collection<Callable<T>> tasks, 
+                               long timeout, TimeUnit unit) 
+            throws InterruptedException, ExecutionException, TimeoutException {
+            return e.invokeAny(tasks, timeout, unit);
+        }
+    }
+    
+    /**
+     * A wrapper class that exposes only the ExecutorService and 
+     * ScheduleExecutor methods of a ScheduledExecutorService implementation.
+     */
+    static class DelegatedScheduledExecutorService
+            extends DelegatedExecutorService 
+            implements ScheduledExecutorService {
+        private final ScheduledExecutorService e;
+        DelegatedScheduledExecutorService(ScheduledExecutorService executor) {
+            super(executor);
+            e = executor;
+        }
+        public ScheduledFuture<?> schedule(Runnable command, long delay,  TimeUnit unit) {
+            return e.schedule(command, delay, unit);
+        }
+        public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
+            return e.schedule(callable, delay, unit);
+        }
+        public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay,  long period, TimeUnit unit) {
+            return e.scheduleAtFixedRate(command, initialDelay, period, unit);
+        }
+        public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay,  long delay, TimeUnit unit) {
+            return e.scheduleWithFixedDelay(command, initialDelay, delay, unit);
+        }
+    }
+
+        
+    /** Cannot instantiate. */
+    private Executors() {}
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Executors.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Future.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Future.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Future.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Future.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,133 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+
+/**
+ * A <tt>Future</tt> represents the result of an asynchronous
+ * computation.  Methods are provided to check if the computation is
+ * complete, to wait for its completion, and to retrieve the result of
+ * the computation.  The result can only be retrieved using method
+ * <tt>get</tt> when the computation has completed, blocking if
+ * necessary until it is ready.  Cancellation is performed by the
+ * <tt>cancel</tt> method.  Additional methods are provided to
+ * determine if the task completed normally or was cancelled. Once a
+ * computation has completed, the computation cannot be cancelled.
+ * If you would like to use a <tt>Future</tt> for the sake
+ * of cancellability but not provide a usable result, you can
+ * declare types of the form <tt>Future&lt;?&gt;</tt> and
+ * return <tt>null</tt> as a result of the underlying task.
+ *
+ * <p>
+ * <b>Sample Usage</b> (Note that the following classes are all
+ * made-up.) <p>
+ * <pre>
+ * interface ArchiveSearcher { String search(String target); }
+ * class App {
+ *   ExecutorService executor = ...
+ *   ArchiveSearcher searcher = ...
+ *   void showSearch(final String target) throws InterruptedException {
+ *     Future&lt;String&gt; future = executor.submit(new Callable&lt;String&gt;() {
+ *         public String call() { return searcher.search(target); }
+ *     });
+ *     displayOtherThings(); // do other things while searching
+ *     try {
+ *       displayText(future.get()); // use future
+ *     } catch (ExecutionException ex) { cleanup(); return; }
+ *   }
+ * }
+ * </pre>
+ *
+ * The {@link FutureTask} class is an implementation of <tt>Future</tt> that 
+ * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>. 
+ * For example, the above construction with <tt>submit</tt> could be replaced by:
+ * <pre>
+ *     FutureTask&lt;String&gt; future =
+ *       new FutureTask&lt;String&gt;(new Callable&lt;String&gt;() {
+ *         public String call() {
+ *           return searcher.search(target);
+ *       }});
+ *     executor.execute(future);
+ * </pre>
+ * @see FutureTask
+ * @see Executor
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> The result type returned by this Future's <tt>get</tt> method
+ */
+public interface Future<V> {
+
+    /**
+     * Attempts to cancel execution of this task.  This attempt will
+     * fail if the task has already completed, already been cancelled,
+     * or could not be cancelled for some other reason. If successful,
+     * and this task has not started when <tt>cancel</tt> is called,
+     * this task should never run.  If the task has already started,
+     * then the <tt>mayInterruptIfRunning</tt> parameter determines
+     * whether the thread executing this task should be interrupted in
+     * an attempt to stop the task.
+     *
+     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
+     * task should be interrupted; otherwise, in-progress tasks are allowed
+     * to complete
+     * @return <tt>false</tt> if the task could not be cancelled,
+     * typically because it has already completed normally;
+     * <tt>true</tt> otherwise
+     */
+    boolean cancel(boolean mayInterruptIfRunning);
+
+    /**
+     * Returns <tt>true</tt> if this task was cancelled before it completed
+     * normally.
+     *
+     * @return <tt>true</tt> if task was cancelled before it completed
+     */
+    boolean isCancelled();
+
+    /**
+     * Returns <tt>true</tt> if this task completed.  
+     *
+     * Completion may be due to normal termination, an exception, or
+     * cancellation -- in all of these cases, this method will return
+     * <tt>true</tt>.
+     * 
+     * @return <tt>true</tt> if this task completed.
+     */
+    boolean isDone();
+
+    /**
+     * Waits if necessary for the computation to complete, and then
+     * retrieves its result.
+     *
+     * @return the computed result
+     * @throws CancellationException if the computation was cancelled
+     * @throws ExecutionException if the computation threw an
+     * exception
+     * @throws InterruptedException if the current thread was interrupted
+     * while waiting
+     */
+    V get() throws InterruptedException, ExecutionException;
+
+    /**
+     * Waits if necessary for at most the given time for the computation
+     * to complete, and then retrieves its result, if available.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return the computed result
+     * @throws CancellationException if the computation was cancelled
+     * @throws ExecutionException if the computation threw an
+     * exception
+     * @throws InterruptedException if the current thread was interrupted
+     * while waiting
+     * @throws TimeoutException if the wait timed out
+     */
+    V get(long timeout, TimeUnit unit)
+        throws InterruptedException, ExecutionException, TimeoutException;
+}
+
+
+

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/Future.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/FutureTask.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/FutureTask.java?rev=421111&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/FutureTask.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/FutureTask.java Tue Jul 11 21:12:04 2006
@@ -0,0 +1,276 @@
+/*
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/licenses/publicdomain
+ */
+
+package java.util.concurrent;
+import java.util.concurrent.locks.*;
+
+/**
+ * A cancellable asynchronous computation.  This class provides a base
+ * implementation of {@link Future}, with methods to start and cancel
+ * a computation, query to see if the computation is complete, and
+ * retrieve the result of the computation.  The result can only be
+ * retrieved when the computation has completed; the <tt>get</tt>
+ * method will block if the computation has not yet completed.  Once
+ * the computation has completed, the computation cannot be restarted
+ * or cancelled.
+ *
+ * <p>A <tt>FutureTask</tt> can be used to wrap a {@link Callable} or
+ * {@link java.lang.Runnable} object.  Because <tt>FutureTask</tt>
+ * implements <tt>Runnable</tt>, a <tt>FutureTask</tt> can be
+ * submitted to an {@link Executor} for execution.
+ *
+ * <p>In addition to serving as a standalone class, this class provides
+ * <tt>protected</tt> functionality that may be useful when creating
+ * customized task classes.
+ *
+ * @since 1.5
+ * @author Doug Lea
+ * @param <V> The result type returned by this FutureTask's <tt>get</tt> method
+ */
+public class FutureTask<V> implements Future<V>, Runnable {
+    /** Synchronization control for FutureTask */
+    private final Sync sync;
+
+    /**
+     * Creates a <tt>FutureTask</tt> that will upon running, execute the
+     * given <tt>Callable</tt>.
+     *
+     * @param  callable the callable task
+     * @throws NullPointerException if callable is null
+     */
+    public FutureTask(Callable<V> callable) {
+        if (callable == null)
+            throw new NullPointerException();
+        sync = new Sync(callable);
+    }
+
+    /**
+     * Creates a <tt>FutureTask</tt> that will upon running, execute the
+     * given <tt>Runnable</tt>, and arrange that <tt>get</tt> will return the
+     * given result on successful completion.
+     *
+     * @param  runnable the runnable task
+     * @param result the result to return on successful completion. If
+     * you don't need a particular result, consider using
+     * constructions of the form:
+     * <tt>Future&lt;?&gt; f = new FutureTask&lt;Object&gt;(runnable, null)</tt>
+     * @throws NullPointerException if runnable is null
+     */
+    public FutureTask(Runnable runnable, V result) {
+        sync = new Sync(Executors.callable(runnable, result));
+    }
+
+    public boolean isCancelled() {
+        return sync.innerIsCancelled();
+    }
+    
+    public boolean isDone() {
+        return sync.innerIsDone();
+    }
+
+    public boolean cancel(boolean mayInterruptIfRunning) {
+        return sync.innerCancel(mayInterruptIfRunning);
+    }
+    
+    public V get() throws InterruptedException, ExecutionException {
+        return sync.innerGet();
+    }
+
+    public V get(long timeout, TimeUnit unit)
+        throws InterruptedException, ExecutionException, TimeoutException {
+        return sync.innerGet(unit.toNanos(timeout));
+    }
+
+    /**
+     * Protected method invoked when this task transitions to state
+     * <tt>isDone</tt> (whether normally or via cancellation). The
+     * default implementation does nothing.  Subclasses may override
+     * this method to invoke completion callbacks or perform
+     * bookkeeping. Note that you can query status inside the
+     * implementation of this method to determine whether this task
+     * has been cancelled.
+     */
+    protected void done() { }
+
+    /**
+     * Sets the result of this Future to the given value unless
+     * this future has already been set or has been cancelled.
+     * @param v the value
+     */ 
+    protected void set(V v) {
+        sync.innerSet(v);
+    }
+
+    /**
+     * Causes this future to report an <tt>ExecutionException</tt>
+     * with the given throwable as its cause, unless this Future has
+     * already been set or has been cancelled.
+     * @param t the cause of failure.
+     */ 
+    protected void setException(Throwable t) {
+        sync.innerSetException(t);
+    }
+    
+    /**
+     * Sets this Future to the result of computation unless
+     * it has been cancelled.
+     */
+    public void run() {
+        sync.innerRun();
+    }
+
+    /**
+     * Executes the computation without setting its result, and then
+     * resets this Future to initial state, failing to do so if the
+     * computation encounters an exception or is cancelled.  This is
+     * designed for use with tasks that intrinsically execute more
+     * than once.
+     * @return true if successfully run and reset
+     */
+    protected boolean runAndReset() {
+        return sync.innerRunAndReset();
+    }
+
+    /**
+     * Synchronization control for FutureTask. Note that this must be
+     * a non-static inner class in order to invoke the protected
+     * <tt>done</tt> method. For clarity, all inner class support
+     * methods are same as outer, prefixed with "inner".
+     *
+     * Uses AQS sync state to represent run status
+     */
+    private final class Sync extends AbstractQueuedSynchronizer {
+        /** State value representing that task is running */
+        private static final int RUNNING   = 1;
+        /** State value representing that task ran */
+        private static final int RAN       = 2;
+        /** State value representing that task was cancelled */
+        private static final int CANCELLED = 4;
+
+        /** The underlying callable */
+        private final Callable<V> callable;
+        /** The result to return from get() */
+        private V result;
+        /** The exception to throw from get() */
+        private Throwable exception;
+
+        /** 
+         * The thread running task. When nulled after set/cancel, this
+         * indicates that the results are accessible.  Must be
+         * volatile, to serve as write barrier on completion.
+         */
+        private volatile Thread runner;
+
+        Sync(Callable<V> callable) {
+            this.callable = callable;
+        }
+
+        private boolean ranOrCancelled(int state) {
+            return (state & (RAN | CANCELLED)) != 0;
+        }
+
+        /**
+         * Implements AQS base acquire to succeed if ran or cancelled
+         */
+        protected int tryAcquireShared(int ignore) {
+            return innerIsDone()? 1 : -1;
+        }
+
+        /**
+         * Implements AQS base release to always signal after setting
+         * final done status by nulling runner thread.
+         */
+        protected boolean tryReleaseShared(int ignore) {
+            runner = null;
+            return true; 
+        }
+
+        boolean innerIsCancelled() {
+            return getState() == CANCELLED;
+        }
+        
+        boolean innerIsDone() {
+            return ranOrCancelled(getState()) && runner == null;
+        }
+
+        V innerGet() throws InterruptedException, ExecutionException {
+            acquireSharedInterruptibly(0);
+            if (getState() == CANCELLED)
+                throw new CancellationException();
+            if (exception != null)
+                throw new ExecutionException(exception);
+            return result;
+        }
+
+        V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {
+            if (!tryAcquireSharedNanos(0, nanosTimeout))
+                throw new TimeoutException();                
+            if (getState() == CANCELLED)
+                throw new CancellationException();
+            if (exception != null)
+                throw new ExecutionException(exception);
+            return result;
+        }
+
+        void innerSet(V v) {
+            int s = getState();
+            if (ranOrCancelled(s) || !compareAndSetState(s, RAN))
+                return;
+            result = v;
+            releaseShared(0);
+            done();
+        }
+
+        void innerSetException(Throwable t) {
+            int s = getState();
+            if (ranOrCancelled(s) || !compareAndSetState(s, RAN)) 
+                return;
+            exception = t;
+            result = null;
+            releaseShared(0);
+            done();
+        }
+
+        boolean innerCancel(boolean mayInterruptIfRunning) {
+            int s = getState();
+            if (ranOrCancelled(s) || !compareAndSetState(s, CANCELLED)) 
+                return false;
+            if (mayInterruptIfRunning) {
+                Thread r = runner;
+                if (r != null)
+                    r.interrupt();
+            }
+            releaseShared(0);
+            done();
+            return true;
+        }
+
+        void innerRun() {
+            if (!compareAndSetState(0, RUNNING)) 
+                return;
+            try {
+                runner = Thread.currentThread();
+                innerSet(callable.call());
+            } catch(Throwable ex) {
+                innerSetException(ex);
+            } 
+        }
+
+        boolean innerRunAndReset() {
+            if (!compareAndSetState(0, RUNNING)) 
+                return false;
+            try {
+                runner = Thread.currentThread();
+                callable.call(); // don't set result
+                runner = null;
+                return compareAndSetState(RUNNING, 0);
+            } catch(Throwable ex) {
+                innerSetException(ex);
+                return false;
+            } 
+        }
+    }
+}

Propchange: incubator/harmony/enhanced/classlib/trunk/sandbox/juc-proposal/concurrent/src/main/java/java/util/concurrent/FutureTask.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message