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+"] ";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With