[concurrency-interest] Ensure Callable.call is invoked from constructing thread?

Kris Schneider kris at dotech.com
Fri Jun 9 10:31:18 EDT 2006


I need to ensure that a Callable is called from the same thread within 
which it was constructed:

public class Processor implements Callable {
   private Object ctx;

   public Processor(Object threadSensitiveContext) {
     if (threadSensitiveContext == null) {
       throw new NullPointerException("threadSensitiveContext cannot be null");
     }
     this.ctx = threadSensitiveContext;
     // Store id/ref of current thread
   }

   public Object call() throws Exception {
     if (this.ctx == null) {
       throw new IllegalStateException("ctx has already been processed - 
this Callable can only be called once");
     }

     // Ensure id/ref of current thread is the same as stored id/ref

     Object result = null;
     try {
       // Use this.ctx to produce result
     } finally {
       this.ctx = null;
     }
     return result;
   }
}

The two approaches that immediately came to mind were to use a reference 
object or System.identityHashCode(Thread.currentThread()). Any thoughts on 
which might be better or if there are other approaches that are better 
still? Thanks.

-- 
Kris Schneider <mailto:kris at dotech.com>
D.O.Tech       <http://www.dotech.com/>


More information about the Concurrency-interest mailing list