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 8616995
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T05:45:07+00:00 2026-06-12T05:45:07+00:00

I’m trying to make a thread safe singleton cache of ConcurrentHashMaps using a Google

  • 0

I’m trying to make a thread safe singleton cache of ConcurrentHashMaps using a Google Guava Cache. Each of these maps will contain a List. The List will only be read ONCE after all threads which could add to it have executed. I’m wondering if my implementation (specifically where I update an item) is thread safe/how to improve it. Is there a better way to do this without using a synchronized block?

public enum MyCache {
    INSTANCE;

    private static Cache<Integer, ConcurrentHashMap<String, List>> cache = 
        CacheBuilder.newBuilder()
            .maximumSize(1000)
            .build();

    private static AtomicInteger uniqueCount = new AtomicInteger(0);

    private final Object mutex = new Object();

        //Create a new unique ConcurrentHashMap
    public Integer newMapItem(){

        Integer key = uniqueCount.incrementAndGet();

        //We dont care if something exists
        cache.put(
            key,
            new ConcurrentHashMap<String, List>()
        );


        return key;
    }

    public void expireMapItem(int key){
        cache.invalidate(key);
    }

    public Integer add(int cacheKey, String mapListKey, int value){

        synchronized(mutex){
            ConcurrentMap<String, List> cachedMap = cache.getIfPresent(cacheKey);
            if (cachedMap == null){
                //We DONT want to create a new map automatically if it doesnt exist
                return null;
            }


            List mappedList = cachedMap.get(mapListKey);

            if(mappedList == null){



                List newMappedList = new List();
                mappedList = cachedMap.putIfAbsent(mapListKey, newMappedList);
                if(mappedList == null){
                    mappedList = newMappedList;
                }
            }
            mappedList.add(value);
            cachedMap.replace(mapListKey, mappedList);

            cache.put(
                cacheKey,
                cachedMap
            );

        }
        return value;
    }



}

  • 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-06-12T05:45:08+00:00Added an answer on June 12, 2026 at 5:45 am

    If multiple threads can write to a given List (which should be a List<Integer>, since you are adding ints to it), you’ll need to synchronize on something. However, you don’t need that global lock. Moreover, you seem to think that Cache and ConcurrentHashMap copy the objects you put into them and get from them, since you’re putting them again once they have been updated, but they don’t: they hold references to what you put into them.

    I’d change the add() method this way:

    public Integer add(int cacheKey, String mapListKey, int value) {
        // You don't need to synchronize here, since the creation of the map is not
        // synchronized. So either it has been created before, or it hasn't, but there
        // won't be a concurrency problem since Cache is thread-safe.
        ConcurrentMap<String, List<Integer>> cachedMap = cache.getIfPresent(cacheKey);
        if (cachedMap == null){
            // We DON'T want to create a new map automatically if it doesn't exist
            return null;
        }
    
        // CHM is of course concurrent, so you don't need a synchronized block here
        // either.
        List<Integer> mappedList = cachedMap.get(mapListKey);
        if (mappedList == null) {
            List<Integer> newMappedList = Lists.newArrayList();
            mappedList = cachedMap.putIfAbsent(mapListKey, newMappedList);
            if (mappedList == null) {
                mappedList = newMappedList;
            }
        }
    
        // ArrayList is not synchronized, so that's the only part you actually need to
        // guard against concurrent modification.
        synchronized (mappedList) {
            mappedList.add(value);
        }
    
        return value;
    }
    

    Actually, I’d create a Cache of LoadingCaches, instead of a Cache of ConcurrentHashMap, it makes the code in add() more simple, moving the creation of the List to the CacheLoader implementation. You can still expose the LoadingCaches as Maps using the asMap() method. I’ve removed some boxing/unboxing as well.

    EDIT: changed the return type of add() to boolean instead of int which doesn’t work with the original return null (when the return type was Integer). No need for a potential NPE.

    public enum MyCache {
        INSTANCE;
    
        private static Cache<Integer, LoadingCache<String, List<Integer>>> cache =
                CacheBuilder.newBuilder()
                        .maximumSize(1000)
                        .build();
    
        private static AtomicInteger uniqueCount = new AtomicInteger(0);
    
        public int newMapItem() {
            int key = uniqueCount.incrementAndGet();
    
            //We dont care if something exists
            cache.put(key, CacheBuilder.newBuilder().build(ListCacheLoader.INSTANCE));
    
            return key;
        }
    
        public void expireMapItem(int key) {
            cache.invalidate(key);
        }
    
        public boolean add(int cacheKey, String mapListKey, int value) {
            // You don't need to synchronize here, since the creation of the map is not
            // synchronized. So either it has been created before, or it hasn't, but there
            // won't be a concurrency problem since Cache is thread-safe.
            LoadingCache<String, List<Integer>> cachedMap = cache.getIfPresent(cacheKey);
            if (cachedMap == null) {
                // We DON'T want to create a new map automatically if it doesn't exist
                return false;
            }
    
            List<Integer> mappedList = cachedMap.getUnchecked(mapListKey);
    
            // ArrayList is not synchronized, so that's the only part you actually need to
            // guard against concurrent modification.
            synchronized (mappedList) {
                mappedList.add(value);
            }
    
            return true;
        }
    
        private static class ListCacheLoader extends CacheLoader<String, List<Integer>> {
            public static final ListCacheLoader INSTANCE = new ListCacheLoader();
    
            @Override
            public List<Integer> load(String key) {
                return Lists.newArrayList();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm making a simple page using Google Maps API 3. My first. One marker
Basically, what I'm trying to create is a page of div tags, each has
I am trying to understand how to use SyndicationItem to display feed which is
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

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.