I have this code which gets and sets the data in the cache using the synchronized block. I want to know if is there is any way by which I can remove the synchronized block, and if the code is optimal or can be further optimized.

AtomicReferenceTest<Integer> cachedIntRef = new AtomicReference<Integer>();
boolean wasCached = true;
Integer cachedInt = cachedIntRef.get();
if (cachedInt == null) {
    synchronized(cachedIntRef) {
        cachedInt = cachedIntRef.get();
        if (cachedInt == null) {
            wasCached = false;
            // Make DB call to get the data and update the cache.
            cachedInt = dao.getIntFromDB();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.