In java, return value within synchronized block seems like bad style. Does it really matter?

后端 未结 2 1997
不思量自难忘°
不思量自难忘° 2020-12-30 18:12

I have a Collections.synchronizedList of WeakReference, _components;

I wrote something like the following, expecting the complier to complain:

public         


        
相关标签:
2条回答
  • 2020-12-30 18:57

    It's absolutely fine - as is returning from a loop, or from a try block which has an appropriate finally block. You just need to be aware of the semantics, at which point it makes perfect sense.

    It's certainly simpler code than introducing a local variable for the sake of it:

    // Ick - method body is now more complicated, with no benefit
    public boolean addComponent2(Component e) {
        boolean ret;
        synchronized (_components) {
            ret = _components.add(new WeakReference<Component>(e));
        }
        return ret;
    }
    
    0 讨论(0)
  • 2020-12-30 19:13

    There is nothing wrong with returning inside a synchronized block. The lock will be released correctly.

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