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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T15:08:26+00:00 2026-05-19T15:08:26+00:00

I’m wondering what the best approach to this problem would be. I have an

  • 0

I’m wondering what the best approach to this problem would be. I have an (abstractly speaking) simple method that calls a webservice and stores the result in a local in-memory cache, something like:

public Document callWebservice(SomeObject parameter) { 
    Document result = cache.get(parameter);
    if (result == null) {
        result = parse(retrieve(parameter));
        cache.put(result);
    }
    return result;
}

Now, if the Document is in the cache, it can just return without problems, fine. In a singlethreaded environment, this approach works fine too. However, in a multithreaded environment, it turns out that each thread will turn to the ‘else’ bit, and call the webservice several times.

I could chuck a synchronized block in the ‘else’ part, but I believe that’s too ‘wide’ of a lock – the whole method will be unavailable for calling threads even though they call completely different things.

It’s fine if the webservice is called twice, as long as the request is different (i.e. the SomeObject parameter, in this case).

Now, question: What’s the best approach to take in this case?

I’ve thought of storing the parameter in a (threadsafe) collection object. If the parameter’s contents are the same, it’ll produce the same hashCode / equals outcome and will be found in the collection object, indicating that another thread is already processing this request. If that would be the case, the calling thread could be paused until the webservice returns. (I’d have to figure out how to make the calling thread wait though). Would this work with a lock on the SomeObject parameter object? e.g:

private Map<SomeObject, SomeObject> currentlyProcessingItems = new ConcurrentHashMap<SomeObject, SomeObject>();
public Document callWebservice(SomeObject parameter) {
    if (currentlyProcessedItems.contains(parameter)) {
        parameter = currentlyProcessedItems.get(parameter);
    } else {
        currentlyProcessedItems.putIfAbsent(parameter);
    }
    synchronized(parameter) {
        Document result = cache.get(parameter);
        if (result == null) {
            Document result = parse(retrieve(parameter));
            cache.put(result);
        }
        currentlyProcessedItems.remove(parameter);
        return result;
    }
}

(note: logic for keeping track of the currently processing requests, usage of ConcurrentHashMap and the locking may be suboptimal or outright wrong)

No, I never actually finished reading the book on threading. I should.

I’m pretty sure this particular problem is quite common, I just wasn’t able to find the answer. What is a situation like this called (i.e. locking on a specific object), if I may ask?

  • 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-19T15:08:27+00:00Added an answer on May 19, 2026 at 3:08 pm

    I was thinking of the problem myself, especially when retrieve(parameter) takes a long time (For me, it is connect to a server to check authentication, process/filter request at back end, etc.). Now I have not tried this out myself yet, but for the the sake of discussion, how does this sound?

    To use the cache, one has to call new MyCache(key).getValue() from a thread, since getValue will be locked in the method getCacheValue() until this value becomes available (to all waiting threads).

    public class MyCache {
    
        private final static HashMap cacheMap = new HashMap();  // One Map for all
        private final static Vector fetchList = new Vector();   // One List for all
    
        private Object cacheValue;
        private boolean waitingState;
    
        public MyCache (Object key) {
            if (cacheMap.containsKey (key)) {       // somebody has done it
                cacheValue = cacheMap.get (key);
            } else {
                waitingState = true;
                if (fetchInProgress (key, false))   // someone else is doing it
                    return;
                new Thread (new MyFetch (key)).start();
        }}
    
        synchronized private static boolean fetchInProgress (Object key, boolean remove) {
            if (remove) {
                fetchList.remove (key);
            } else {
                boolean fetchingNow = fetchList.contains (key);
                if (fetchingNow)
                    return true;
                fetchList.addElement (key);
            }
            return false;
        }
    
        public Object getValue () {
            if (waitingState)
                getCacheValue (true);
            return cacheValue;
        }
    
        synchronized private void getCacheValue (boolean waitOnLock) {
            if (waitOnLock) {
                while (waitingState) {
                    try {
                        wait();
                    } catch (InterruptedException intex) {
            }}} else {
                waitingState = false;
                notifyAll();
        }}
    
        public class MyFetch implements Runnable {
            private Object fetchKey;
            public MyFetch (Object key) {
                fetchKey = key;     // run() needs to know what to fetch
            }
    
            public void run () {        // Grab the resource, handle exception, etc.
                Object fetchedValue = null; 
                // so it compiles, need to replace by callWebService (fetchKey);
                cacheMap.put (fetchKey, fetchedValue);  // Save for future use
                fetchInProgress (fetchKey, true);   // Remove from list
                getCacheValue (false);          // Notify waiting threads
    }}}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have just tried to save a simple *.rtf file with some websites and
this is what i have right now Drawing an RSS feed into the php,
I have a small JavaScript validation script that validates inputs based on Regex. I
I have this code to decode numeric html entities to the UTF8 equivalent character.
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
This could be a duplicate question, but I have no idea what search terms

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.