[concurrency-interest] Questions on ConcurrentHashMap

Tim Peierls tim at peierls.net
Fri Nov 30 11:58:11 EST 2007


Sorry if this is obvious to everyone else, but I don't understand the
interrupt handling in the while loop. How does it terminate?

--tim

On Nov 30, 2007 3:10 AM, Jed Wesley-Smith <jed at atlassian.com> wrote:

>  I have a utility class for that encapsulates lockless lazy loading stuff.
> It locks only when multiple threads call get while run is occuring
> (FutureTask implementation).
>
> /**
>  * Thread-safe lock-less reference that is not constructed until required.
>  * <p>
>  * Implement create() in implementation.
>  */
> public abstract class LazyLoadedReference<V>
> {
>     private final AtomicReference<FutureTask<V>> ref = new
> AtomicReference<FutureTask<V>>();
>
>     public final V get()
>     {
>         FutureTask<V> future = ref.get();
>         if (future == null)
>         {
>             // create a Future
>             future = new FutureTask<V>(new Callable<V>()
>             {
>                 public V call() throws Exception
>                 {
>                     return create();
>                 }
>             });
>             // set the reference only if it is still null
>             ref.compareAndSet(null, future);
>             // get the future that ref now holds (may be different to
> above
>             future = ref.get();
>         }
>         while (true)
>         {
>             try
>             {
>                 future.run();
>                 return future.get();
>             }
>             catch (InterruptedException interruptAndTryAgain)
>             {
>                 Thread.currentThread().interrupt();
>             }
>             catch (ExecutionException e)
>             {
>                 throw new RuntimeException(e);
>             }
>         }
>     }
>
>     /**
>      * The object factory method, guaranteed to be called once and only
> once.
>      */
>     protected abstract V create();
> }
>
> Then you simply need to implement create() in your implementation.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: /pipermail/attachments/20071130/8d00985d/attachment.html 


More information about the Concurrency-interest mailing list