1

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.

Community
  • 1
  • 1
Raj
  • 692
  • 2
  • 9
  • 23

2 Answers2

3

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.

  • Why 1st method will not work? I think it will work since only one thread can go inside the block and there i will write count++. – Raj Mar 23 '14 at 08:04
  • @Raj: It would work. Sort of. Til some schmuck decides to synchronize on `CarSold.class` -- which is perfectly legal, but will cause everything else that wants to create a `CarSold` to wait . If you want to lock, then lock on something private (and preferably final). – cHao Mar 23 '14 at 08:06
  • Something like by creating private Object variable? – Raj Mar 23 '14 at 08:10
  • 1
    @Raj: Exactly. Though you'd need to make it `static` as well, in this case. – cHao Mar 23 '14 at 08:12
0
"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.

Mak
  • 596
  • 5
  • 10