0

I am socket-programming a chat client-server in Java. I need to share variables between clients. I tried to use Singleton Design Pattern, but it I get a different instance of the Singleton class every time I run a new instance of the client class.

Here is my code. I need to share clients between clients, so that each one knows all the others.

private LinkedHashMap<String, String> clients = new LinkedHashMap<String, String>();

private static ClientListModel instance = null;

private ClientListModel() {
    System.out.println("NEW INSTANCE!");
}

public static ClientListModel getInstance() {
    if (instance == null)
        instance = new ClientListModel();

    return instance;
}

"NEW INSTANCE!" is being printed out every time I run my client code, and in effect I get an empty clients LinkedHashMap.

What is the proper way to share data between two or more running instances of the same class?

Thank you!

user3903214
  • 203
  • 1
  • 9
  • How is your getInstance() method being invoked? Is it invoked from server? How many instance of server is running? Would you provide code on how your getInstance() is called? And also, you may refer [this answer](http://stackoverflow.com/a/70835/2829759) for java singleton – user2829759 Mar 30 '15 at 01:20
  • getInstance() is being invoked from client. Only one instance of server is running. – user3903214 Mar 30 '15 at 01:22
  • If you are running this in a web server it may load this class for each session. This will mean each user has their own copy of this class and these fields. – Peter Lawrey Mar 30 '15 at 01:42
  • The Singleton pattern is only effective within a single VM instance -- and there are ways to break it even then. If you want clients and server to share a single object despite running in different VMs, and even on different machines, then you're looking for [RMI](https://docs.oracle.com/javase/tutorial/rmi/). – John Bollinger Mar 30 '15 at 02:21

1 Answers1

0

In my opinion, you should make sure the synchronization of threads. So you can change the code like this.

public synchronized static  ClientListModel getInstance() {
    if (instance == null)
        instance = new ClientListModel();

    return instance;
}
uttp
  • 92
  • 6