Reputation: 598
Currently I am trying to understand synchronized
in Java getting to this java doc example under synchronized statements
the example with the class MsLunch
and the two instance variables c1 and c2
.
It states:
Suppose, for example, class
MsLunch
has two instance fields,c1
andc2
, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update ofc1
from being interleaved with an update ofc2
— and doing so reduces concurrency by creating unnecessary blocking.
To me this sounds like c1 and c2
are not allowed to be used together. That is the reason why both statements which are incrementing c1 and c2
have to be synchronized. But why do they say in the next sentence that there is no reson to prevent an update of c1
from being interleaved with an update of c2
. This sentences makes absolutely no sense to me. First they say they are not used together and now it is ok to increment c1
while at the same time c2
is being incremented.
Can someone please elaborate this paragraph to me.
Bear in mind that I am no native English speaker and there could be in fact a language problem in understanding this issue.
Upvotes: 1
Views: 60
Reputation: 91
All updates of these fields must be synchronized, but there's no reason to prevent an update of
c1
from being interleaved with an update ofc2
— and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.
Quote from the javadoc.
They state that there is no reason to prevent an update of c1
from being interleaved with an update of c2
, because there is no relation between them (they seem to be independent). And so, they provide different lock Objects for both of them, meaning that you can update both c1 and c2
at the same time.
I'm not sure if this is enough to make you understand, if so, please comment below so we can discuss further.
Upvotes: 0
Reputation: 691635
c1 and c2 are two completely independant counters. A thread should be able to increament c1 while another thread increments c2. If you simply synchronized the inc1() and inc2() method, you would prevent thread 1 to increment c1 while thread 2 is incrementing c2 (and vice-versa). This would have a negative impact on performance. So you use two separate locks to synchronize each incrementation.
If the value of c2 for example depended on the value of c1, then you would have to use a single lock to avoid race conditions.
Upvotes: 3