Is there a difference between synchronized (UserDefine.class) and synchronized (define1.getClass ())?
I am learning Java MutliThread these days, I came across a problem. Is there a difference between synchronized (UserDefine.class) and synchronized (define1.getClass ())?
define1 is an instance of UserDefine class.
Thank you in advance:)
If it define1
stores a reference to an object of a specific type UserDefine
, there is no difference. Both expressions
UserDefine.class
and
define1.getClass()
will result in the same instance Class
. Therefore, there would be no difference.
If define1
stores a reference to an object of any other type (or null
) then there will be a difference. The corresponding thread will block the monitor on another object or will NullPointerException
(for the case null
).
Small difference:
UserDefine.class
always refers to a UserDefine.class object
define1.getClass();
may, in your case, always return UserDefine.class, but often in programming, if you or someone else comes later, perhaps subclassing UserDefine, in your code it may not return what you expect.