Skip to content

Instantly share code, notes, and snippets.

@Silvenga
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Silvenga/1a9e989c2f3abfb7e2a6 to your computer and use it in GitHub Desktop.
Save Silvenga/1a9e989c2f3abfb7e2a6 to your computer and use it in GitHub Desktop.
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