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

  • Home
  • SEARCH
  • 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 163371
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T11:33:21+00:00 2026-05-11T11:33:21+00:00

Suppose I want to lock based on an integer id value. In this case,

  • 0

Suppose I want to lock based on an integer id value. In this case, there’s a function that pulls a value from a cache and does a fairly expensive retrieve/store into the cache if the value isn’t there.

The existing code isn’t synchronized and could potentially trigger multiple retrieve/store operations:

//psuedocode public Page getPage (Integer id){    Page p = cache.get(id);    if (p==null)    {       p=getFromDataBase(id);       cache.store(p);    } } 

What I’d like to do is synchronize the retrieve on the id, e.g.

   if (p==null)    {        synchronized (id)        {         ..retrieve, store        }    } 

Unfortunately this won’t work because 2 separate calls can have the same Integer id value but a different Integer object, so they won’t share the lock, and no synchronization will happen.

Is there a simple way of insuring that you have the same Integer instance? For example, will this work:

 syncrhonized (Integer.valueOf(id.intValue())){ 

The javadoc for Integer.valueOf() seems to imply that you’re likely to get the same instance, but that doesn’t look like a guarantee:

Returns a Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

So, any suggestions on how to get an Integer instance that’s guaranteed to be the same, other than the more elaborate solutions like keeping a WeakHashMap of Lock objects keyed to the int? (nothing wrong with that, it just seems like there must be an obvious one-liner than I’m missing).

  • 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. 2026-05-11T11:33:21+00:00Added an answer on May 11, 2026 at 11:33 am

    You really don’t want to synchronize on an Integer, since you don’t have control over what instances are the same and what instances are different. Java just doesn’t provide such a facility (unless you’re using Integers in a small range) that is dependable across different JVMs. If you really must synchronize on an Integer, then you need to keep a Map or Set of Integer so you can guarantee that you’re getting the exact instance you want.

    Better would be to create a new object, perhaps stored in a HashMap that is keyed by the Integer, to synchronize on. Something like this:

    public Page getPage(Integer id) {   Page p = cache.get(id);   if (p == null) {     synchronized (getCacheSyncObject(id)) {       p = getFromDataBase(id);       cache.store(p);     }   } }  private ConcurrentMap<Integer, Integer> locks = new ConcurrentHashMap<Integer, Integer>();  private Object getCacheSyncObject(final Integer id) {   locks.putIfAbsent(id, id);   return locks.get(id); } 

    To explain this code, it uses ConcurrentMap, which allows use of putIfAbsent. You could do this:

      locks.putIfAbsent(id, new Object()); 

    but then you incur the (small) cost of creating an Object for each access. To avoid that, I just save the Integer itself in the Map. What does this achieve? Why is this any different from just using the Integer itself?

    When you do a get() from a Map, the keys are compared with equals() (or at least the method used is the equivalent of using equals()). Two different Integer instances of the same value will be equal to each other. Thus, you can pass any number of different Integer instances of ‘new Integer(5)‘ as the parameter to getCacheSyncObject and you will always get back only the very first instance that was passed in that contained that value.

    There are reasons why you may not want to synchronize on Integer … you can get into deadlocks if multiple threads are synchronizing on Integer objects and are thus unwittingly using the same locks when they want to use different locks. You can fix this risk by using the

      locks.putIfAbsent(id, new Object()); 

    version and thus incurring a (very) small cost to each access to the cache. Doing this, you guarantee that this class will be doing its synchronization on an object that no other class will be synchronizing on. Always a Good Thing.

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

Sidebar

Ask A Question

Stats

  • Questions 70k
  • Answers 70k
  • 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
  • added an answer Two potential solutions. Method 1: If you must use the… May 11, 2026 at 12:55 pm
  • added an answer If you already know C, Perl and Java then in… May 11, 2026 at 12:55 pm
  • added an answer EDIT This information is out of date. EDIT: I think… May 11, 2026 at 12:55 pm

Related Questions

Suppose I want to open a file in an existing Emacs session using su
Suppose I want to implement a reasonably efficient 'keyword recognition algorithm', that is first
Suppose I want to create a set of observers based on type. That is
Suppose I want to count the lines of code in a project. If all
Suppose I am writing an application in C++ and C#. I want to write
Unchecked exceptions are alright if you want to handle every failure the same way,
This is a detail question for C#. Suppose I've got a class with an
The problem I have is this: I have a table (just an example) with
C++/CLI helpfully generates the IDisposable scaffolding for you when you implement a destructor on

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.