Reputation: 2123
While I was working on a class which required random number generation, I was thinking about a way to create just one Random object for multiple uses.
I read about static factories in effective java and came up with this, but the more I think about, the less logic I see in this. Is this the best way? And does this make sure only one Random object gets created?
public static Random newInstance() {
return new Random();
}
public static void generateRandom() {
Random rand = newInstance();
//...
}
Another way is initialising it in the constructor, although I'm not sure if this is the best practice?
public static Random rand = new Random();
Upvotes: 0
Views: 86
Reputation: 23002
If your application is single threaded than yes it is fine to use singleton pattern without synchronization, other then that for multi threaded environment if you want single instance than you need synchronization in your newInstanceMethod
or you can declare constant private static final Random = new Random()
as well and return it from your static
newInstance
method.
Note that Random
class is thread safe and no need to worry about the thread safety, but you should follow the singleton pattern properly to make your application can have single Object
during run time in multi threaded environment.
And does this make sure only one Random object gets created?
Currently you are returning new instance every time. If you want only single instance you can have.
private static final Random RANDOM = new Random()
public static Random newInstance() {
return RANDOM;
}
Upvotes: 1
Reputation: 15855
public static final SecureRandom rand = new SecureRandom();
would be the best way to go.
Every time that you call your newInstance()
you're going to construct a new object, which incurs overhead and starts over with a new seed.
In your generateRandom()
your rand
instance will be local to the scope of that method, which may be the better solution if you only need a random number generator for that method. That depends on what else you are doing.
I tend to use static factories for cases where there is more complicated or expensive logic than just constructing an object. Suppose you're going to construct an object and then read some files from disk and load that data into the object. This would be good to do in a static factory because you can specify some exceptions that might occur (IOException
) and generally it's not expected that a constructor is an expensive operation involving something like reading files.
What are static factory methods?
Upvotes: 2