sdgfsdh
sdgfsdh

Reputation: 37121

In Java, is `synchronized` equivalent to `synchronized (this)`?

I was looking through the source code for DatagramSocket and I found this:

public void disconnect() {
    synchronized (this) {
        if (isClosed())
            return;
        if (connectState == ST_CONNECTED) {
            impl.disconnect ();
        }
        connectedAddress = null;
        connectedPort = -1;
        connectState = ST_NOT_CONNECTED;
    }
}

My understanding of synchronized methods is that they lock on this. So is the code equivalent to the following?

public synchronized void disconnect() {
    if (isClosed())
        return;
    if (connectState == ST_CONNECTED) {
        impl.disconnect ();
    }
    connectedAddress = null;
    connectedPort = -1;
    connectState = ST_NOT_CONNECTED;
}

Is there a reason why the language designers chose not to use a synchronized method here?

Upvotes: 4

Views: 718

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27190

Is there a reason why the language designers chose not to use a synchronized method here?

I don't know their minds, but in my mind, the first way is better. I really dislike the phrase "synchronized method", because methods are not what we need to protect with synchronization.

We need to protect data.

The entire point of synchronized blocks, is that often, in order to advance the state of the program, one thread must create a temporary, invalid state. With appropriate use of synchronized we can prevent any other thread from seeing the invalid state. It means synchronizing not just the block of code that is changing the state, but also, any other block of code that can examine the state.


I believe that the idea for synchronized methods came from a paper published in the 1970s describing monitors. https://en.wikipedia.org/wiki/Monitor_%28synchronization%29 A monitor basically is an object whose methods are all atomic. This was a useful abstraction when computer scientists were beginning to explore and formalize ways of thinking about parallel programming; but in a lot of practical applications, the "monitor" idea is too strict: It's hard to make the most efficient use of a multiprocessor system using only monitors.

Upvotes: 2

NPE
NPE

Reputation: 500893

Yes, the two code snippets are equivalent.

We can only guess why whoever wrote this code chose the more verbose version. It could be someone's personal preference, or a historical artefact. For example, it might have previously been synchronized(someObject) or might have only covered part of the method, and whoever refactored the method didn't convert the synchronized section into a synchronized method.

Upvotes: 5

Related Questions