Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 365781
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T13:34:12+00:00 2026-05-12T13:34:12+00:00

I was recently looking for a way to implement a doubly buffered thread-safe cache

  • 0

I was recently looking for a way to implement a doubly buffered thread-safe cache for regular objects.

The need arose because we had some cached data structures that were being hit numerous times for each request and needed to be reloaded from cache from a very large document (1s+ unmarshalling time) and we couldn’t afford to let all requests be delayed by that long every minute.

Since I couldn’t find a good threadsafe implementation I wrote my own and now I am wondering if it’s correct and if it can be made smaller… Here it is:

package nl.trimpe.michiel

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Abstract class implementing a double buffered cache for a single object.
 * 
 * Implementing classes can load the object to be cached by implementing the
 * {@link #retrieve()} method.
 * 
 * @param <T>
 *            The type of the object to be cached.
 */
public abstract class DoublyBufferedCache<T> {

    private static final Log log = LogFactory.getLog(DoublyBufferedCache.class);

    private Long timeToLive;

    private long lastRetrieval;

    private T cachedObject;

    private Object lock = new Object();

    private volatile Boolean isLoading = false;

    public T getCachedObject() {
        checkForReload();
        return cachedObject;
    }

    private void checkForReload() {
        if (cachedObject == null || isExpired()) {
            if (!isReloading()) {
                synchronized (lock) {
                    // Recheck expiration because another thread might have
                    // refreshed the cache before we were allowed into the
                    // synchronized block.
                    if (isExpired()) {
                        isLoading = true;
                        try {
                            cachedObject = retrieve();
                            lastRetrieval = System.currentTimeMillis();
                        } catch (Exception e) {
                            log.error("Exception occurred retrieving cached object", e);
                        } finally {
                            isLoading = false;
                        }
                    }
                }
            }
        }
    }

    protected abstract T retrieve() throws Exception;

    private boolean isExpired() {
        return (timeToLive > 0) ? ((System.currentTimeMillis() - lastRetrieval) > (timeToLive * 1000)) : true;
    }

    private boolean isReloading() {
        return cachedObject != null && isLoading;
    }

    public void setTimeToLive(Long timeToLive) {
        this.timeToLive = timeToLive;
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T13:34:12+00:00Added an answer on May 12, 2026 at 1:34 pm

    What you’ve written isn’t threadsafe. In fact, you’ve stumbled onto a common fallacy that is quite a famous problem. It’s called the double-checked locking problem and many such solutions as yours (and there are several variations on this theme) all have issues.

    There are a few potential solutions to this but imho the easiest is simply to use a ScheduledThreadExecutorService and reload what you need every minute or however often you need to. When you reload it put it into the cache result and the calls for it just return the latest version. This is threadsafe and easy to implement. Sure it’s not on-demand loaded but, apart from the initial value, you’ll never take a performance hit while you retrieve the value. I’d call this over-eager loading rather than lazy-loading.

    For example:

    public class Cache<T> {
      private final ScheduledExecutorsService executor =
        Executors.newSingleThreadExecutorService();
      private final Callable<T> method;
      private final Runnable refresh;
      private Future<T> result;
      private final long ttl;
    
      public Cache(Callable<T> method, long ttl) {
        if (method == null) {
          throw new NullPointerException("method cannot be null");
        }
        if (ttl <= 0) {
          throw new IllegalArgumentException("ttl must be positive");
        }
        this.method = method;
        this.ttl = ttl;
    
        // initial hits may result in a delay until we've loaded
        // the result once, after which there will never be another
        // delay because we will only refresh with complete results
        result = executor.submit(method);
    
        // schedule the refresh process
        refresh = new Runnable() {
          public void run() {
            Future<T> future = executor.submit(method);
            future.get();
            result = future;
            executor.schedule(refresh, ttl, TimeUnit.MILLISECONDS);
          }
        }
        executor.schedule(refresh, ttl, TimeUnit.MILLISECONDS);
      }
    
      public T getResult() {
        return result.get();
      }
    }
    

    That takes a little explanation. Basically, you’re creating a generic interface for caching the result of a Callable, which will be your document load. Submitting a Callable (or Runnable) returns a Future. Calling Future.get() blocks until it returns (completes).

    So what this does is implement a get() method in terms of a Future so initial queries won’t fail (they will block). After that, every ‘ttl’ milliseconds the refresh method is called. It submits the method to the scheduler and calls Future.get(), which yields and waits for the result to complete. Once complete, it replaces the ‘result’ member. Subsequence Cache.get() calls will return the new value.

    There is a scheduleWithFixedRate() method on ScheduledExecutorService but I avoid it because if the Callable takes longer than the scheduled delay you will end up with multiple running at the same time and then have to worry about that or throttling. It’s easier just for the process to submit itself at the end of a refresh.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 429k
  • Answers 430k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Using wc (GNU coreutils) 7.4: wc -L filename gives: 101… May 15, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer You're missing a rule, just required won't do. Use 'notEmpty'… May 15, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer You can use whatever you feel is appropriate for the… May 15, 2026 at 1:46 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.