Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization help in Java

looking at http://download.eclipse.org/jetty/stable-7/xref/com/acme/ChatServlet.html, I don't seem to understand why there needs to be a synchronization block in a synchronized method, like so:

private synchronized void chat(HttpServletRequest request,HttpServletResponse response,String username,String message)
throws IOException
{
    Map<String,Member> room=_rooms.get(request.getPathInfo());
    if (room!=null)
    {
        // Post chat to all members
        for (Member m:room.values())
        {
            synchronized (m)
            {
                m._queue.add(username); // from
                m._queue.add(message);  // chat

                // wakeup member if polling
                if (m._continuation!=null)
                {
                    m._continuation.resume();
                    m._continuation=null;
                }
            }
        }
    }

Why does m need to be synchronized (again?) if the whole method is already thread-safe?

Thank you for any insight.

like image 353
David Titarenco Avatar asked Jun 21 '26 12:06

David Titarenco


2 Answers

The synchronized method "chat(...)" synchronizes on it's instance object whereas the synchronized(m) synchronizes on the "m" object - so they are synchronizing on two different objects. Basically it's making sure that some other servlet object isn't messing with the same Member instance at the same time.

like image 121
Marc Novakowski Avatar answered Jun 23 '26 01:06

Marc Novakowski


When whole method is synchronized the lock is obtained on the this object. But the synchronized block obtains lock only on the member currently being used in iteration.

like image 29
Chandra Sekar Avatar answered Jun 23 '26 02:06

Chandra Sekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!