• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Better way of random number generation using multiple threads

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I am using the following code to generate the random number. This code still gives the same number for multiple threads. I need better way of generating a random number with no ambiguity with multiple threads.
======================================================================
private String generateRandomDocName() {
int nDigits = 9;
String rNumber = "";
rNumber = getRandomString ("1234567890ABCDEF", nDigits);
}
private String getRandomString (String charset, int length) {
Random rnd = new Random (System.currentTimeMillis());
StringBuffer sb = new StringBuffer(length);
int nChars = charset.length();
int rndIdx;
for (int i = 0; i < length; i++)
{
rndIdx = rnd.nextInt(nChars);
sb.append(charset.substring(rndIdx, rndIdx + 1));
}
return sb.toString();
}
===============================================================
Any inputs on this will help me.

Thanks and Regards,
Naresh
 
Sheriff
Posts: 22772
130
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can check out java.util.UUID.
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What's the code to run this in multiple threads?
 
naresh babu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Code will be called from the sevlet.
 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Multiple threads call getRandomString() at the same time ?

Try adding the thread id for seed:
 
Master Rancher
Posts: 4660
63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could also simply make rnd a static final variable. Though it's not really documented, Random is designed to be used safely by multiple concurrent threads, ensuring that each gets a different random number.
 
Mike Simmons
Master Rancher
Posts: 4660
63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually using thread id that way seems risky. You could easily have two threads with similar ids calling this method at similar times, that get the same seed. You could probably avoid this by including a large multiplier for the id:

Yes, this will overflow and truncate, but I don't see that as a problem. The point is, you'll get unique seeds for each thread.

It's a bit wasteful to create a new Random for every method call, anyway. In the event that the single static Random is a performance bottleneck, I'd use a static ThreadLocal to create one Random per thread, initialized as above.
 
Rancher
Posts: 4803
7
Mac OS X VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Mike Simmons:
It's a bit wasteful to create a new Random for every method call, anyway. In the event that the single static Random is a performance bottleneck, I'd use a static ThreadLocal to create one Random per thread, initialized as above.



Its a bit wasteful to create a new Random for each thread. They can all share a common one. Its not a big deal when you use Random, but when you use SecureRandom, there is significant startup overhead.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, as of Java 5+ you will get a more random number (with multiple Random instances) by using:
Random rnd = new Random();
instead of
Random rnd = new Random(System.currentTimeMillis());

The new implementation of Random uses System.nanoTime() plus a static incrementing seed to initialize the random number, which will give a lot more granularity than currentTimeMillis(). From the API "This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor" whereas when you provide the seed you are setting "the initial value of the internal state of the pseudorandom number generator" and so will get the same sequence of numbers if you provide the same seed (which you can if the threads are run in quick succession).

So you are better off:
1) Using a single Random object that all threads share
2) Using the Random(void) constructor rather than providing your own seed.
 
Mike Simmons
Master Rancher
Posts: 4660
63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Pat]: Its a bit wasteful to create a new Random for each thread. They can all share a common one. Its not a big deal when you use Random, but when you use SecureRandom, there is significant startup overhead.

For most situations, I agree. I did say, if accessing the single static is a performance bottleneck. It probably isn't. But it's possible it might be, and there are some scenarios in which the ThreadLocal solution may give better performance. Of course it's also more complicated, so by all means, using a single static Random should be the first choice. That's why I suggested it.

[Steve]: Also, as of Java 5+ you will get a more random number (with multiple Random instances) by using:

Ah yes, I'd forgotten that they added the uniquifier in 5. Thanks.
[ September 13, 2008: Message edited by: Mike Simmons ]
 
They weren't very bright, but they were very, very big. Ad contrast:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic