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.
synchronized(CarSold.class)
Can this 2 approach solves the problem ? And is there is any other way?
Thanks.
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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments