3

I am implementing a backend service using Java. I chose to apply the Singleton pattern because there should be only one service running. However, this service is also a Socket.IO client thus there must be some kind of event being triggered when server pushed. But the event should be synchronized in queue.

I think my implementation is not correct. Tt seems that synchronized(this) block is NOT protecting the Backend object but rather the Emitter.Listener object.

private static synchronized BackendServer getInstance()
{
    if(instance == null) {
        instance = new BackendServer();
        try {
            socket = IO.socket(host_name+":"+port_frontend);
            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                }
            }).on("event1", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    try {
                        synchronized(this) { <--Which object is synchronized?
                            String timestamp = getCurrentTime();
                            String logging = "["+timestamp+"] ";
Aditya W
  • 652
  • 8
  • 20
loudking
  • 115
  • 4
  • Shouldn't the socket be created by an instance method of `BackendServer`? If it is the server, then style-wise you shouldn't create the socket separately from it. – RealSkeptic Sep 20 '16 at 09:09

1 Answers1

3

In the line you quoted, this indeed refers to the Emitter.Listener instance. So you are creating a synchronized block which uses the new Emitter.Listener instance as monitor. This is probably not what you want. If you want to synchronize on another object, you can put that in your synchronized block.

As a side remark, note that synchronized blocks do not protect objects. They make sure that the synchronized block (or any other synchronzied block with the same monitor) is not concurrently visisted by a different thread. If the same object has other non-synchornized code, that can be concurrently executed.

Hoopje
  • 12,677
  • 8
  • 34
  • 50
  • @RealSkeptic. Right. I missed that, thanks. I'll edit the answer. – Hoopje Sep 20 '16 at 09:00
  • Hi thanks for your reply. I do want to synchronize on BackendServer object. Can you please show me some code on how to achieve this inside the Emitter.Listener function? – loudking Sep 20 '16 at 09:23