Start United States USA — software Thread-Safety of an Iterator Over a Stream of SecureRandom Values

Thread-Safety of an Iterator Over a Stream of SecureRandom Values

245
0
TEILEN

This article reviews using an iterator for a stream from Java’s SecureRandom, showing how a stream iterator from a thread-safe object is not always thread-safe.
Join the DZone community and get the full member experience. I recently experienced an interesting scenario involving Java streams. The scenario surprised me or at least wasn’t what I was expecting. Maybe I was unwary in my implementation, but it still gave me another reason to consider things before using streams. Not that streams are bad, on the contrary, I think they are a great feature in the Java language and very cool to use, in the right place. The need was the following: provide a mechanism to indefinitely generate unique IDs that are “secure,” in the sense that they are hard to predict. At any point in time, an ID needs to be generated and handed over to a client. To implement this, the Java platform’s SecureRandom felt like the best way to do it. It provides random values that strong from a security standpoint supports a very wide range of values, and is thread-safe. The problem is that even if the range is vast (say you’re generating long values, so you have 264 values), this may still not be enough, and you want to ensure no duplicate values are even generated. One way to do this is to store values in some structure such as a concurrent set (you could generate one using a ConcurrentHashMap).

Continue reading...