What is the point of the synchronization here?
Why not just use mConnectedThread.write(out)?
The code snippet is from the BluetoothChat sample for Android (found here)
/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
Synchronization is needed to ensure that you don’t have inconsistent state.
Without the synchronization, the code would be:
Now, if the connection where to close between the if statement check and the method invocation,
mConnectedThreadmight be assigned to null, before the method invocation execution. That would result into aNullPointerException.