Java singleton enum programmed to the interface? - java

This is my first post on here so I will try to be precise. This is for a university project, we have to create a fish tank simulation on top of an OO architecture that we individually make. I'm exploring the uses of singletons and have found them quite useful, however reading online the way I currently implement it is not thread safe.
The way I currently implement it (Think its the lazy method) Note: We have to go through the interface
public interface myInterface
{
void foo();
}
public class myClass implements myInterface
{
private static myInterface instance;
private myClass(){}
private static myInterface Instance()
{
if(instance == null)
instance = new myClass();
return instance;
}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
This works well however its not thread safe I could add the synchronized keyword to the getter but I've read that that is quite heavy on the system and I have quite a few singletons.
private synchronized static myInterface Instance()
{
if(instance == null)
instance = new myClass();
return instance;
}
I have then moved on to an enum singleton which is thread safe and is not heavy on the system however I am unsure on how to program it to the interface.
public enum myClass implements myInterface
{
INSTANCE;
private myClass(){}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
In programming to the interface I mean when I call the singleton I can only access methods that are in the interface (please correct me if I'm referring to this wrongly). This is where the way I have done the enum singleton fails. For example: With the lazy singleton I can not call this as its not in the interface:
myClass.Instance().bar();
But it can call this which is correct, as it is in the interface.
myClass.Instance().foo();
With the enum however I can call this and its not programming to the interface
myClass.INSTANCE.bar();
I understand why its doing this as the class is an enum so it will be able to call everything in that enum class. So after this long post which I apologise for, the main question is: Can I make the enum version only call methods that are declared in the interface?
If it can't how heavy is a synchronized method on the system, I would have around 4-6 of them?
Please Note: Even though this is for a university project we are only running the simulation on one thread so it does not even need to be thread safe. I don't quite understand multi-threading but I thought it would be a good learning opportunity.

You can always hide your enum implementation as well if you prefer the enum route:
public interface Singleton {
void foo();
}
public final class SingletonAccessor {
public static Singleton getInstance() {
return SingletonImpl.INSTANCE;
}
private SingletonAccessor() {
}
private enum SingletonImpl implements Singleton {
INSTANCE;
public void foo() {
// ...
}
public void bar() {
// ...
}
}
}
EDIT
As pointed out by Peter Lawrey in the comments, you can even use an enum for the SingletonAccessor :)
public enum SingletonAccessor {
SINGLETON;
public Singleton get() {
return SingletonImpl.INSTANCE;
}
private enum SingletonImpl implements Singleton {
INSTANCE;
public void foo() {
// ...
}
public void bar() {
// ...
}
}
}

You can cast it to the interface or
myInterface my = myClass.INSTANCE;
my.foo();
You can still use a method like
myClass.getInstance().foo();
But this isn't a real solution IMHO.
Can I make the enum version only call methods that are declared in the interface?
Ultimately you have to decide which methods you want on the instance which are public. If you make a method or field public, you can access it and if you don't want to be able to access it, make it private.
At some point you have to trust you know what you are doing and you do things for a reason. You don't have to think up ways to prevent yourself from call code you wrote.

just simply change your singleton class this way:
public class myClass implements myInterface
{
private static myInterface instance = new myClass();
private myClass(){}
private static myInterface Instance()
{
return instance;
}
public void foo()
{
//Do stuff
}
public void bar()
{
//Do More Stuff
}
}
this will assure that the singleton object will be created at class-loading time, and you don't need to worry about race-conditions in the Instance() method

Try looking at java.util.concurrent.atomic.AtomicReference. Specifically compareAndSet.
instance.compareAndSet(null, new MyClass());
That is if your instance field is null, set to new object, if not null, leave intact. Should be less heavy.

Related

Conflicting understanding on singleton implementations

From my understanding a Singleton is a single instance of a class that lasts throughout the span of an applications lifetime. However I've seen a few different implementations of the systems, but I'm always informed that they're wrong, flawed, etc. etc. I'm going to post the two that I see more commonly and I would like to hear opinions/fact based on which implementation is better and why. Implementations are compilable.
Implementation A:
public class Foo {
private static Foo singelton;
private Foo() {
System.out.println("Bar");
}
public static Foo getSingleton() {
if(singleton == null) singleton = new Foo();
return singleton;
}
public static void main(String[] args) {
Foo.getSingleton();
}
}
Implementation B:
public class Foo {
private static final Foo singelton = new Foo();
private Foo() {
if(singelton != null) {
throw new IllegalStateException("Singleton class was already constructed.");
}
System.out.println("Bar");
}
public static void main(String[] args) {
// NOT REQUIRED
}
}
You'll notice in Implementation B that the Singleton instance is final. Also, because of the static implementation the main(String[]) method never needs to construct an instance of this class.
Both Implementation A and B will yield the same results.
Opinions?
Hey you have shown two implementations, the second one is called early initialization and first one is called lazy initialization, as it is initializing the class on demand only.
However your first initialization will fail in multi-threaded environment.
You have to use double checked locking to secure your code.
E. g. :
public class EagerSingleton {
private static volatile EagerSingleton instance = null;
// private constructor
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
if (instance == null) {
synchronized (EagerSingleton.class) {
// Double check
if (instance == null) {
instance = new EagerSingleton();
}
}
}
return instance;
}
}
For morer details please check :
http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/

Java method with abstract class as parameter that returns instance of the child class

I'm sure this will have been asked before but I can't find it after searching for some time.
I need a function that will do something like the following:
public static AbstractClass createClass(Class<AbstractClass> theChildClass, int someVariable){
AbstractClass theInstance = theChildClass.newInstance(someVariable);
return theInstance;
}
Then on AbstractClass I want to define it like so:
public abstract class AbstractClass{
private int someVariable;
public AbstractClass(int someVariable){
this.someVariable = someVariable;
initOnChild();
}
protected abstract void initOnChild();
}
Then on the child classes I ideally don't want to define the "public ChildClass(int someVariable){}" method, so they look like this:
public class ChildClass extends AbstractClass{
#Override
protected void initOnChild(){
//do some stuff
}
}
The ideal outcome I'm after is being able to call the method like so:
ChildClass theInstance = UtilityClass.createClass(ChildClass.class, 1);
Is this even possible? Any solutions or advice much appreciated.
No. Constructors are not inherited (and therefore are not members in JLS-speak). Depending on the situation you may want to apply the strategy pattern, say.
(ObNote: Generally it's considered a bad idea to call overrideable methods from constructors, and reflection is almost always a really bad idea.)
No, but there is a solution.
First the problem with calling an overriden method in the constructor:
abstract class A {
A() {
init();
}
protected abstract void init();
}
class B extends A {
public String x = null;
public String y;
#Override
protected void init() {
x = "x";
y = "y";
}
}
public static void main(String[] args) {
B b = new B();
System.out.printf("x=%s, y=%s%n", b.x, b.y);
}
Would of course give:
x=null, y=y
in B() - all fields zeroed
super() called, A()
in A() B.init() called
in B() field initialisations are done
But it is not obvious from reading superficially, and when using fields in the base class, can become less obvious.
Now the solution.
As you have a static factory method, maybe place this method in AbstractClass. Then it can call init after construction.
public static <T extends AbstractClass> T create(Class<T> childClass, int param) {
T instance = childClass.getConstructor().newInstance();
instance.init(param);
return instance;
}
This executes the default constructor.
Should this still be unsatisfactory, then it just might be that some datastructure does not reside in the correct inheritance level, or should be restructured.

Avoid Object Creation in Java

How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.
One Approach is that i can throw IllegalArgumentException in the constructor of class A.
is there any other?
public class A{
public A(){
throw IllegalArguementException();
}
}
The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.
class Test
{
private Test(){ }
public static Test getTestInstance(){
return new Test();
}
}
Hope it helps,
You can do it by making the constructor private.
class A
{
int i;
private A()
{
i=1;
}
public static A getInstance()
{
return new A();
}
}
class B
{
A a;
public B()
{
/* a=new A(); //This doesn't compile */
}
}
Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
public enum SingletonEnum {
INSTANCE;
public void doYourStuff(){
System.out.println("Singleton using Enum");
}
}
And this can be called from clients :
public static void main(String[] args) {
SingletonEnum.INSTANCE.doYourStuff();
}
You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.
private A() {}
Make the constructor private.

How to construct a Non Instantiable AND Non Inheritable Class in Java

The question says it all.
I know the Singleton pattern (with final to its class) is a solution. Are there any other possible ways we can achieve this?
Abstracting a class makes it non-instantiable. Making it final makes it non-inheritable.
How do we combine both?
public final class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
/*public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}*/
public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
private static SingletonObject ref;
}
Code Ref: http://www.javacoffeebreak.com/articles/designpatterns/index.html
Make the constructor private:
public final class Useless {
private Useless() {}
}
A private constructor is the normal object-oriented solution. However, it would still be possible to instantiate such a class using reflection, like this:
Constructor<Useless> con = Useless.class.getDeclaredConstructor();
con.setAccessible(true); // bypass "private"
Useless object = con.newInstance();
To prevent even reflection from working, throw an exception from the constructor:
public final class Useless {
private Useless() {
throw new UnsupportedOperationException();
}
}
You mean a class with static methods only? Class cannot be both final and abstract. But you can use private constructor to make it not instantinable.
final class StaticOnly {
private StaticOnly() {
throw new RuntimeException("Do not try to instantiate this");
}
public static String getSomething() {
return "something";
}
}
Below example will work to. You won't instantiate it because it's abstract. You won't inherit it because there is no way to call super constructor from external subclass (only inner subclass will work)
abstract class StaticOnly {
private StaticOnly() {}
public static String getSomething() {
return "something";
}
}
enum will work too
enum StaticOnly {
S;
public static String getSomething() {
return "something";
}
}
but it always have at least one instance (here it's S).
I would use the simplest Singleton pattern
enum Singleton {
INSTANCE;
}
The enum type is non-instance-able and non-inheritable and the classes initialisation is lazy and thread safe.
To declare there should never be an instance you can also use an enum
enum Utilities {
; // no instances
// add static methods here
}

Reusing class after calling static methods

Suppose I have a class with several static void methods, for example:
class MyClass {
public static void doJob() {
// ...
}
public static void doSmthElse() {
// ...
}
}
how can I modify it to call my static methods like this:
MyClass.doJob().doSmthElse().doJob();
instead of
MyClass.doJob();
MyClass.doSmthElse();
MyClass.doJob();
I know how to do it with non-static methods (just return this), but how to do it with static fields?
Well, you could do this:
// Horrible, don't do it!
class MyClass {
public static MyClass doJob() {
// ...
return null;
}
public static MyClass doSmthElse() {
// ...
return null;
}
}
At that point your code will compile, as Java allows access to static methods "via" references. The fact that you're returning null is irrelevant, because the compiler will only look at the compile-time type of the expression MyClass.doJob() in order to work out which doSmthElse() method to call; the static method will then be called without examining the return value at all.
But please don't do this - it's a really nasty code smell, as your code looks like it's doing one thing when it's actually doing another.
Options:
Just live with your more verbose calls
Extract the static methods into a class where it makes sense for them to be instance methods (this may well improve testability etc as well)
Import the methods statically
Create a larger method in MyClass which calls the three methods one after another.
You can make this class singleton and do
return getInstance();
in every method
You can create a dummy instance of you class and return this. You will use static members of class, but return a reference to regular instance (just for fun, just for code style). But I wouldn't like to use this approach.
class MyClass {
private static int data = 0;
private static MyClass link = null;
public static void doJob() {
// do job with static data such as "data"
return checkMe();
}
public static void doSmthElse() {
// do someting else with static data such as "data"
return checkMe();
}
private MyClass static void checkMe() {
if (link == null) link = new MyClass();
return link;
}
}
It is immpossible because there is no object you can return.

Categories