简体   繁体   中英

Is my code thread safe?

In my java application, I have a string ( MySingleton.getInstance().myString ) which gets updated based on user actions. In this application, there is a TCP server which sends the value of this string to all connected clients whenever the value of the string changes.

Each client socket gets its own thread. Here is the thread code.

    public void run() {
        try {
            PrintStream printStream = new PrintStream(hostThreadSocket.getOutputStream(), true);
            while (true) {
                synchronized (MySingleton.getInstance()) {
                 printStream.println(MySingleton.getInstance().myString);
                    try {
                        MySingleton.getInstance().wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

And here is the code which writes to MySingleton.getInstance().myString .

    public void updateString(String newString) {
        synchronized (MySingleton.getInstance()) {
            MySingleton.getInstance().myString = newString;
            MySingleton.getInstance().notifyAll();
        }
    }

I am not familiar with synchronization in java so I am not much confident about my code. Can anybody notice anything wrong?

It should be fine, provided that MySingleton.getInstance() always returns the same object.

If the method call returns different objects at different points in time, then you may get exceptions due to synchronizing on one instance, and then calling wait or notify on a different instance. In addition, there may be memory hazards because you are not synchronizing on the object that you are accessing / updating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM