Synchronizing on an object in java, then changing the value of the synchronized-on variable

后端 未结 4 558
误落风尘
误落风尘 2020-12-11 00:41

I came across a code like this

synchronized(obj) {

   obj = new Object();

}

Something does not feel right about this , I am unable to ex

4条回答
  •  一个人的身影
    2020-12-11 00:58

    It's a uncommon usage but seems to be of valid in same scenarios. One I found in the codebase of JmDNS:

    public Collection getDNSEntryList(String name) {
        Collection entryList = this._getDNSEntryList(name);
        if (entryList != null) {
            synchronized (entryList) {
                entryList = new ArrayList(entryList);
            }
        } else {
            entryList = Collections.emptyList();
        }
        return entryList;
    }
    

    What it does is to synchonize on the returned list so this list does not get modified by others and then makes a copy of this list. In this special situation the lock is only needed for the original object.

提交回复
热议问题