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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T06:57:07+00:00 2026-06-01T06:57:07+00:00

Are these methods getNewId() & fetchIdsInReserve() thread safe ? public final class IdManager {

  • 0

Are these methods getNewId() & fetchIdsInReserve() thread safe ?

public final class IdManager {

    private static final int NO_OF_USERIDS_TO_KEEP_IN_RESERVE = 200;

    private static final AtomicInteger regstrdUserIdsCount_Cached = new AtomicInteger(100);
    private static int noOfUserIdsInReserveCurrently = 0;

    public static int getNewId(){                   
          synchronized(IdManager.class){
              if (noOfUserIdsInReserveCurrently <= 20)
                      fetchIdsInReserve();    

              noOfUserIdsInReserveCurrently--;
          }
          return regstrdUserIdsCount_Cached.incrementAndGet();
    }


    private static synchronized void fetchIdsInReserve(){
        int reservedInDBTill = DBCountersReader.readCounterFromDB(....); // read column from DB 

        if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) throw new Exception("Unreserved ids alloted by app before reserving from DB");

        if (DBUpdater.incrementCounter(....)) //if write back to DB is successful
              noOfUserIdsInReserveCurrently += NO_OF_USERIDS_TO_KEEP_IN_RESERVE;
    }

}
  • 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-01T06:57:08+00:00Added an answer on June 1, 2026 at 6:57 am

    No.

    If 21 threads comes in here

          synchronized(IdManager.class){
              if (noOfUserIdsInReserveCurrently <= 20)
                      fetchIdsInReserve();    
    
              noOfUserIdsInReserveCurrently--;
          }
    

    and wait while another 180 threads proceed through the top and through the line below, then by the time the 21st thread reaches the line below, there will be no user ids in reserve when the 21st thread from the first group calls

          return regstrdUserIdsCount_Cached.incrementAndGet();
    

    EDIT:

    Here’s the initial state on class load:

    regstrdUserIdsCount_Cached = 100
    noOfUserIdsInReserveCurrently = 0
    

    Let’s assume that the write back to the DB is always successful. If it isn’t, this code is clearly broken, because it still allocates an ID in that case.

    The first thread comes through, and calls fetch because there are no ids in reserve.

    regstrdUserIdsCount_Cached = 100
    noOfUserIdsInReserveCurrently = 0
    

    assuming the DB returns 100 as the initial ID, after the method completes without contention

    regstrdUserIdsCount_Cached = 101
    noOfUserIdsInReserveCurrently = 199
    

    Now, let’s assume 178 more threads go through without contention

    regstrdUserIdsCount_Cached = 279
    noOfUserIdsInReserveCurrently = 21
    

    if that thread is preempted by another that comes through after it exits the synchronized block but before it decrements the atomic int, the preempting thread will trigger a fetch.

    Since noOfUserIdsInReserveCurrently has not been decremented by the thread that was pre-empted,

    (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) 
    

    will be false.

    Assuming that exception indicates a failure mode, we have a failure during one interleaving that is not thrown during other-interleavings. Therefore, the code is not thread-safe.

    The solution is to consistently access regstrdUserIdsCount_Cached inside the critical section. In that case, it need not be an atomic int, but can simply be a non-final int.

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

Sidebar

Related Questions

I use these methods to get the text: public static string[] GetAllTextInSlide(SlidePart slidePart) {
Is there any difference between these methods of declaring and setting a public class
I've some class with these methods: public class TestClass { public void method1() {
Is there a functional difference between these methods? public static void main(String[] args) {
These two methods appear to behave the same to me public IEnumerable<string> GetNothing() {
I have these 2 methods in the View class. the drawRect method always gets
Consider a class with these methods: - (id) initWithFrame: (CGRect) frame { if (!(self
I am running a WCF service with these methods, public string UploadInspections(Inspection[] inspections) public
I want to have a class with dynamic methods. From these arrays: prefix =
I have a class with a bunch of methods. some of these methods are

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.