Java 1.4 synchronization: only allow one instance of method to run (non blocking)?

后端 未结 4 971
眼角桃花
眼角桃花 2021-01-20 05:14

I have a class proposing translations utilities. The translations themselves should be reloaded every 30 minutes. I use Spring Timer support for that. Basically, my class lo

4条回答
  •  走了就别回头了
    2021-01-20 05:35

    This is actually identical to the code that is required to manage the construction of a Singleton (gasp!) when done the classical way:

    if (instance == null) {
      synchronized {
        if (instance == null) {
           instance = new SomeClass();
        }
      }
    }
    

    The inner test is identical to the outer test. The outer test is so that we dont routinely enter a synchronised block, the inner test is to confirm that the situation has not changed since we last made the test (the thread could have been preempted before entering Synchronized).

    In your case:

    if (translationsNeedLoading()) {
      synchronized {
        if (translationsNeedLoading()) {
           loadTranslations();
        }
      }
    }
    

    UPDATE: This way of constructing a singleton will not work reliably under your JDK1.4. For explanation see here. However I think you are you will be OK in this scenario.

提交回复
热议问题