race condition in RandomBasedGenerator?
facboy opened this issue · 3 comments
The below comment is not strictly true, is it? Because of the wonders of hotspot reordering etc, there is the possibility that a thread will see a non-null _sharedRandom that won't be fully constructed. Would it not be better to use volatile (if you want to maintain the side effects), or an AtomicReference (my preference). Both of these will only work in a 1.5+ JVM, 1.4 and below sync is your only choice.
/* Could be synchronized, but since side effects are trivial
* (ie. possibility of generating more than one SecureRandom,
* of which all but one are dumped) let's not add synchronization
* overhead.
*/
rnd = _sharedRandom;
if (rnd == null) {
_sharedRandom = rnd = new SecureRandom();
}
Right, statement is not true (it is a leftover from earlier times when I didn't know full scope of java memory model).
For what it is worth, one more possibility would be to use a wrapper class for singleton as synchronization of class loading is guaranteed by Java memory model. But I agree in that AtomicReference is probably the best choice -- while some aspects of JUG are 1.4 only it's probably pointless to worry too much about pre-1.5 JVMs at this point.
singleton lazy-init holder would prolly be good actually, works on 1.4 VMs and has no overhead at all after the first call.
Ok, implemented using singleton lazy-init holder, will include in 3.1.3.