Search code examples
javaasynchronousatomicnonblockingsynchronized

seeking suggestions/critique for async rebuilding of a resource


Here is the proposed solution (I did search for the same - unsuccessfully)

    public abstract class AsyncCache<T> {

        /**
         * an atomic int is used here only because stamped reference doesn't take a long,
         * if it did the current thread could be used for the stamp.
         */
        private AtomicInteger threadStamp = new AtomicInteger(1);
        private AtomicStampedReference<T> reference = new AtomicStampedReference<T>(null, 0);

        protected abstract T rebuild();

        public void reset() {
            reference.set(null, 0);
        }

        public T get() {
            T obj = reference.getReference();
            if (obj != null) return obj;

            int threadID = threadStamp.incrementAndGet();

            reference.compareAndSet(null, null, 0, threadID);

            obj = rebuild();

            reference.compareAndSet(null, obj, threadID, threadID);

            return obj;

        }

    }

The process should be easy to see - the resource is only built when requested and invalidated by calling reset.

The first thread to request resource inserts its ID into the stamped reference and will then insert its version of the resource once generated UNLESS another reset is called. in case of a subsequent reset the first requesting thread will return a stale version of the resource (is valid use case), and some request started after the latest reset will populate the reference with its result.

Please let me know if I've missed something or if there is a better (faster + simlpler ++ elegant) solution. One thing - the MAX_INT is not handled intentionally - don't believe the prog will live long enough, but certainly easy to do.

Thank you.


Solution

  • Thats defiently not async since requesting thread will block until rebuild() method is complete. Another problem - you don't check value returned from compareAndSet. I believed you need something like this

    if(reference.compareAndSet(null, null, 0, threadID)) { //if resource was already reseted - rebuild
       reference.compareAndSet(null, obj, threadID, threadID);
       obj = rebuild();
    } 
    

    But that approach has another drawback - you have to rebuild entry several times (considering several threads wants that entry at once). You can use future tasks for that case (http://www.codercorp.com/blog/java/simple-concurrent-in-memory-cache-for-web-application-using-future.html) or use MapMaker.