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

Tim Peierls tim at peierls.net
Fri Jun 9 11:14:29 EDT 2006


You could store the thread-sensitive context in a ThreadLocal, set by the
constructor, checked and used in call().

For different approaches to dealing with execution policies like this, see
chapters 6 and 8 of Java Concurrency in Practice (http://jcip.net).

--tim

On 6/9/06, Kris Schneider <kris at dotech.com> wrote:
>
> 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/>
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20060609/f6fc343e/attachment.html 


More information about the Concurrency-interest mailing list