Question

I have a class.

public CarSold{

static int count;

CarSold(){count++;}


// Other code
}

Now this is running in multithreading enviroment. And I read here that constructors are not implicitly syncronized.

In that case, there is a chance that I don't have the correct count of cars sold in the count variable.

What is the way to make sure that it has a correct count?

I can think of 2 ways.

  1. Class level locking inside the constructor using synchronized(CarSold.class)
  2. I can use AtomicInteger.

Can this 2 approach solves the problem ? And is there is any other way?

Thanks.

Was it helpful?

Solution

You don't synchronize a constructor, that doesn't make any sense semantically, you synchronize the access to the variable. Which can happen from anywhere that has access to it.

What you are looking for in this case is AtomicInteger.

OTHER TIPS

"Now this is running in multithreading enviroment. And I read here that constructors are not implicitly syncronized."

You might have already got the logic but just wanted to mention it again. When you synchronize a method, may it be constructor, it creates lock on 'this' object which is still not initialized and null in case if you are trying to synchronize the constructor. But You can create a separate instance object and use a lock on that object. Chances are the instance variable you are trying to use as lock is also not yet initialized. In that case you will get NP exception. Now, important thing is from Java 6 final instance variables are thread safe so use can use a final object for locking in constructor.

If you are locking on XYD.class it will be application wise lock which might be valid in your case but sometimes you need instance level lock and in that case you can use above approach.

Can this 2 approach solves the problem ?

Yes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top