multithreading - What is the use of java.lang.Class and how it relates to static method synchronization? -
i reading static method synchronization in java. read static methods
lock on object of java.lang.class
. trying understand concept of java.lang.class
, role in static method synchronization , have these questions.
i reading blog says every class in java has instance of
java.lang.class
, instances of class share object. instance of java.lang.class describes type of object? role of java.lang.class here? how describes type of object?secondly static method synchronization, need monitor of java.lang.class. why that? why need lock on java.lang.class monitor? why not on instance of our own class example test(my own custom class)?
can elaborate on it. sorry because sounds pretty basic question pretty new concept.
tentative explanation, although admittedly not correct. whatever class c
, when do:
final c c = new c();
two object
s involved here: class<c>
object (which provided via context classloader) , c
instance. c
know class via .getclass()
method (defined in object
).
the fact new
keyword able establish "backlink" correct class
responsibility of jvm implementation. while mentioned in jls, cannot tell where...
now, more point.
if have method declared as:
synchronized void whatever() { somecode(); }
then equivalent (why roughly: see below):
void whatever() { synchronized(this) { somecode(); } }
that is, code synchronized @ instance level.
if method static however, this:
public static synchronized void meh() { someothercode(); }
is equivalent (why roughly: see below):
public static void meh() { synchronized(getclass()) { someothercode(); } }
one thing note class
objects singletons; no matter how many instances of class c
create, .getclass()
return same class
object. try this:
public static void main(final string... args) { final string s1 = "foo"; final string s2 = "bar"; system.out.println(s1.getclass() == s2.getclass()); // true }
add fact getclass()
equivalent this.getclass()
, picture. class
being object
, obeys monitor rules of object
.
and since here refer exact same object, monitor rules apply ;)
now, "roughly": in code written above, logic same; however, depending on how write code, bytecode may differ; jit have in , optimize code paths.
Comments
Post a Comment