Skip to content

Initializer Examples

Hieu T. Le edited this page Nov 4, 2018 · 1 revision

Introduction

Details

  • Initializer-Thread-Safety-Example-1 - Care should be taken to not start a thread within an object constructor (@see Java Concurrency In Practice). The Java memory model does not guarantee that the fields of an object will contain correct references until the constructor returns. But the Initializer requires you to publish a reference to the Initializable during object construction (before the constructor returns). This means Initializer's background thread can see the wrong references. Rather than starting threads in the constructor, the recommended practice is to create a separate initialize() method that is invoked on an object after it is fully constructed, meaning all the java memory model guarantees are in place. The initialize() method can then delegate to Initializer . . . within certain constraints as shown by the other test case.
  • Initializer-Thread-Safety-Example-2 - The Initializer background thread and the main application thread share state (e.g. the reference to the Service instance). Changes to shared state made by one thread are not guaranteed to be visible in other threads unless there is a publication event. Examples of a publication event include:
    1. The use of explicit locking.
    2. Writing to and reading the same volatile reference.
    3. Using a thread-safe container than guarantees safe publication between threads (e.g. java.util.concurrent.BlockingQueue). Users of the initializer and its interface should be aware of these issues when implementing to avoid errors in their system which may be difficult to detect.

Clone this wiki locally