In what situations could an empty synchronized block achieve correct threading semantics?

前端 未结 5 1232
离开以前
离开以前 2020-12-14 16:36

I was looking through a Findbugs report on my code base and one of the patterns that was triggered was for an empty synchronzied block (i.e. synchronized

5条回答
  •  情歌与酒
    2020-12-14 17:07

    Synchronizing does a little bit more than just waiting, while inelegant coding this could achieve the effect required.

    From http://www.javaperformancetuning.com/news/qotm030.shtml

    1. The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
    2. The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
    3. The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).
    4. (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)
    5. The thread releases the lock on the monitor for object this.

提交回复
热议问题