Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is Random Thread Safe ?

 
Tony Collins
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry about anothr THread safety post, but my question is Random.nextLong thread safe. As I have it as I use it as a static member of my data class to get Security Cookies. So I supose does nextLong update Random ?
Tony
 
Arun Kumar
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would do it this way ..
You should have a static WeakHaspMap in the Data class. (May be you are not using a WeakHashMap, but some other Map).
So in the lockRecord method,

There by you dont have to worry about thread safety while generating random numbers. Only the thread which owns the monitor on the WeakHaspMap can generate a random number, the other thread will be on wait().
 
Tony Collins
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's thread safe anyway.
Tony
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Random class does not offer any guarantees about whether a Random object is thread-safe or not; therefore, we must assume it's not inherently therad-safe, and if we require thread safety, we must ensure it ourselves. (Usually through synchronization.) This is true of just about all classes in Java: if you can't find documentation assuring thread safety, assume it's not thread-safe. Note that Math.random() does guarantee it's safe for use by multiple threads (because the Math class provides the necessary synchronization). But the Random class does not.
Arun's code will probalby work, though it's not immediately clear to look at it - we don't know how the Random instance relates to the WeakHashMap. Is it a one-to-one relationship? (Probably.) But it seems more straightforward to sync on the Random instance instead. This makes sense, as it's the thread safety of the Random instance that concerns us. Why sync on something else?
 
Tony Collins
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Random is safe as it's implementation uses the synchronized function next.
Tony
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Random is safe as it's implementation uses the synchronized function next.
Yes, the standard implementations do appear to be safe. (Haven't analyzed it really carefully, but it seems so.) However they neglected to document this fact, and it's not guaranteed for other implementations. So the safest pratice is to assume it's not thread-safe, and synchronize it yourself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic