java - Static versus non-static lock object in synchronized block -


trying visualize , understand synchronization.

  1. what differences between using static lock object (code a) , non-static lock object (code b) synchronized block?
  2. how differ in practical applications?
  3. what pitfalls 1 have other wouldn't?
  4. what criteria determine 1 use?

code a

public class myclass1 {   private static final object lock = new object();   public myclass1() {     //unsync     synchronized(lock) {       //sync     }     //unsync   } } 

code b

public class myclass2 {   private final object lock = new object();   public myclass2() {     //unsync     synchronized(lock) {       //sync     }     //unsync   } } 

note

the above code shows constructors, talk how behavior different in static method , non-static method too. also, advantageous use static lock when synchronized block modifying static member variable?

i looked @ answers in this question, it's not clear enough different usage scenarios are.

the difference simple: if locked-on object in static field, instances of myclass* share lock (i.e. no 2 objects able lock on object @ same time).

if field non-static, each instance have own lock, calls of method on same object lock each other.

when use static lock object:

  • thread 1 calls o1.foo()
  • thread 2 calls o1.foo(), have wait thread 1 finish
  • thread 3 calls o2.foo(), also have wait thread 1 (and 2) finish

when use non-static lock object:

  • thread 1 calls o1.foo()
  • thread 2 calls o1.foo(), have wait thread 1 finish
  • thread 3 calls o2.foo(), can continue, not minding thread 1 , 2

which 1 of you'll need depends on kind of data try protect synchronized block.

as rule of thumb, want lock-object have same static-ness operated-on value. if manipulate non-static values only, you'll want non-static lock object. if manipulate static values only, you'll want static lock object.

when manipulate static , non-static values, it'll become complicated. easy way use static lock object, might increase size of synchronized-block more absolutely necessary , might need more lock contention desired. in cases might need combination of static , non-static lock objects.

in particular case use lock in constructor, ever executed once per instance, non-static lock-object doesn't make sense here.


Comments