Scy
Scy

Reputation: 245

Random shared between instances of an object?

I want to create a lot of instances of an object that uses a random number as part of its initialization, but if I make a massive number of these objects in a loop, most of them will be the same (I think). Can someone clarify? And if I'm correct in my assumption, is there a way to have them share a single Random object?

Upvotes: 1

Views: 1030

Answers (1)

ck1
ck1

Reputation: 5443

Your objects can share a single java.util.Random instance. In fact, this will give you the best performance, versus creating a new instance of Random each time.

If you're dealing with multiple threads, even though java.util.Random is threadsafe, you should consider using ThreadLocalRandom introduced in JDK 1.7 instead, as it will significantly reduce thread contention.

For example:

public class ExampleClass {
    private static final Random random = new Random();

    public ExampleClass() {
        System.out.println("Constructor using random: " + random.nextInt(100));
    }

    public void methodThatUsesRandom() {
        System.out.println("Method using random: " + random.nextInt(100));
    }
}

Upvotes: 2

Related Questions