同步点是什么位置?
为什么不直接使用 mConnectedThread.write(下)
?
在code段是从BluetoothChat样品为Android (这里找到)
/ **
*写的ConnectedThread在非同步的方式
*参数了要写入的字节
* @see ConnectedThread#写入(字节[])
* /
公共无效的write(byte []的输出){
//创建临时对象
ConnectedThreadř;
//该ConnectedThread副本同步
同步(本){
如果(mState = STATE_CONNECTED!)回报;
R = mConnectedThread;
}
//执行写操作不同步
r.write(出);
}
解决方案
需要同步,以确保你没有不一致的状态。
如果没有同步,code将是:
公共无效的write(byte []的输出){
如果(mState = STATE_CONNECTED!)回报;
mConnectedThread.write(出);
}
现在,如果连接在那里关闭if语句检查和方法调用之间, mConnectedThread
可能会被分配到空,方法调用执行之前。这将导致成 NullPointerException异常
。
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:
public void write(byte[] out) {
if (mState != STATE_CONNECTED) return;
mConnectedThread.write(out);
}
Now, if the connection where to close between the if statement check and the method invocation, mConnectedThread
might be assigned to null, before the method invocation execution. That would result into a NullPointerException
.