I am trying to create a Singleton class, which will be accessed from two other classes.Can anyone please tell me whats wrong with the following code? I am just not able to figure out!
import java.util.LinkedList;
public class MessageQueue {
private static final LinkedList<ServerDataEvent> queue = new LinkedList<ServerDataEvent>();;
private static MessageQueue messageQueue = null;
/** A private Constructor prevents any other class from instantiating. */
private MessageQueue() {
}
/** Static 'instance' method */
public static MessageQueue getInstance() {
if (MessageQueue.messageQueue == null) {
System.out.println("Creating MessageQueue instance.");
MessageQueue.messageQueue = new MessageQueue();
}
return MessageQueue.messageQueue;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}
I am accessing the singleton object from other classes like this:
MessageQueue messageQueue = MessageQueue.getInstance();
There are no errors, but
System.out.println("Creating MessageQueue instance.");
is getting executed whenever I do
MessageQueue messageQueue = MessageQueue.getInstance();
EDIT 1
import java.util.LinkedList;
public class MessageQueue {
private static final LinkedList<ServerDataEvent> queue = new LinkedList<ServerDataEvent>();;
private static final MessageQueue messageQueue = new MessageQueue();
/** A private Constructor prevents any other class from instantiating. */
private MessageQueue() {
System.out.println("problem...");
}
/** Static 'instance' method */
public static MessageQueue getInstance() {
return MessageQueue.messageQueue;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}