Can you safely synchronize on a Java method parameter?

前端 未结 1 477
别那么骄傲
别那么骄傲 2020-12-29 06:48

Take this code:

public class MyClass {
    private final Object _lock = new Object();
    private final MyMutableClass _mutableObject = new MyMutableClass()
         


        
1条回答
  •  醉梦人生
    2020-12-29 07:24

    Synchronization is done upon objects, not variables.

    Variables/members [sometimes] contain objects and it is the resulting object contained in [variable] x that is actually synchronized upon in synchronized(x).

    There are a few other issues with thread-visibility of variables (e.g. might read a "stale" object from a variable), but that does not apply here: there is no re-assignment of _lock and the visibility of the initial ("final") assignment is guaranteed. Because of this it is guaranteed that, in this case, the method parameter will always contain the correct (same) object used for the synchronization.

    If the lock object used (where presumably _lock is not final) changes, however, then that would require re-evaluation of the appropriate values/thread-visibility but otherwise does not differ from any cross-thread access.

    Happy coding.

    0 讨论(0)
提交回复
热议问题