Skip to content

Instantly share code, notes, and snippets.

@Silvenga
Last active Aug 29, 2015
Embed
What would you like to do?
package com.silvenga.singleton;
import java.util.Random;
public class RandomSingleton
// Basic interface for a Singleton
public static Random getInstance() {
// Return the instance of Random created in RandomContainer
return Container.randomInstance;
}
// We use an enum for lazy loading. Load a new instance once and only when needed
// Making a Singleton this way prevents any attempt of making multiple instances
private static enum Container {
// Required to prevent compiler optimization
INSTANCE;
// When the Enum is first accessed it will create
// a static instance of Random
private static Random randomInstance = new Random();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment