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.
- Class level locking inside the constructor using
synchronized(CarSold.class)
- I can use AtomicInteger.
Can this 2 approach solves the problem ? And is there is any other way?
Thanks.