Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, you can initialize a static member once and share it across threads, but only if you exercise due care. For example, all <strong><em>init()</em></strong> call sites must be synchronized; that is, <strong><em>init()</em></strong> may only be called from the constructor or from synchronized methods. Alternatively, you may initialize the <strong><em>mapOfConstants</em></strong> variable in a static initializer block. Whichever approach you use, you may also want to consider the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow">java.util.concurrent.ConcurrentHashMap</a> implementation as the concrete type for the <strong><em>mapOfConstants</em></strong> variable since this will avoid headaches later.</p> <p>Failing to exercise due care may cause you to encounter the "double-checked locking" race condition. Also, initializing a static reference variable is usually considered an anti-pattern since, in this case, entries in the map can grow without bound within one activation of the program. Typically, the only acceptable usage for such a reference would be if the contents were, well, constant or if the contents grew very slowly--think logarithmically--over time. Logarithmic growth may be aided by the use of a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/WeakHashMap.html" rel="nofollow">java.util.WeakHashMap</a> or, failing that, the judicious use of <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html" rel="nofollow">weak references</a>.</p> <p>So far, the focus seems to be on initializing the static <strong><em>mapOfConstants</em></strong> variable. But this forgets that the whole purpose of a map is (usually) to store something for later retrieval in O(1) time in the best case. Keep in mind that when store and retrieval operations (on the <strong><em>mapOfConstants</em></strong> variable) cross thread boundaries, then those operations must also be synchronized. Absent synchronization, additions or edits by one thread may be missed by other threads, which could ramify for your program's data integrity.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload