Java synchronized blocks -- lock objects -


in sample code

public class mslunch { private long c1 = 0; private long c2 = 0; private object lock1 = new object(); private object lock2 = new object();  public void inc1() {     synchronized(lock1) {         c1++;     } }  public void inc2() {     synchronized(lock2) {         c2++;     } } } 

on this page,

lock1 , lock2 controlling updates on c1 , c2 resply.

however,

    synchronized(lock2)  

is acquiring lock of object lock1 , releasing when synchronized block

    synchronized(lock1) {         c1++;     } 

is executed.

while block being executed, there may update on member c1 of this object still-- , don't see how update being prevented synchronizing on lock1 in code.

it object lock1 there exclusive access on-- , nothing else(?)

so, how implementation

public void inc1() {     synchronized(lock1) {         c1++;     } } 

in above code different

public void synchronized inc1() {         c1++; } 

or

public void inc1() {     synchronized(c1) {         //do on c1     } } 

when c1 object not primitive?

what missing here ?

note: saw

what difference between synchronized on lockobject , using lock?

and

java synchronized method lock on object, or method?

among other discussions.

implementation 1.

you locking on lock1 object. nothing else needs lock on lock1 can execute. having 2 methods lock on different objects means 2 methods can run concurrently, no 2 threads can run same method concurrently.

implementation 2.

making method synchronized means entire method body implicitly in synchronized(this) block (or synchronized on class object if method static. if both methods synchronized, 1 method prevent other running @ same time, different locking both methods on different objects.

implementation 3.

if c1 object , not primitive, semantics similar implementation 1 - locking on explicit object.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -