简体   繁体   English

android示例蓝牙聊天应用程序中此空赋值的目的是什么

[英]what is the purpose of this null assignment in the android sample bluetooth chat application

I'm just analyzing one of android sample applications - the bluetooth chat: https://developer.android.com/samples/BluetoothChat/project.html . 我只是在分析一个android示例应用程序-蓝牙聊天: https : //developer.android.com/samples/BluetoothChat/project.html I'm looking at the BluetoothChatService class ( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html ), at the connect method. 我正在使用connect方法查看BluetoothChatService类( https://developer.android.com/samples/BluetoothChat/src/com.example.android.bluetoothchat/BluetoothChatService.html )。 There is such piece of code there: 那里有这样一段代码:

public synchronized void connect(BluetoothDevice device, boolean secure) {
    Log.d("@@@", "connect to: " + device);
    // Cancel any thread attempting to make a connection
    if (mState == STATE_CONNECTING) {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }
    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device, secure);
    mConnectThread.start();
    setState(STATE_CONNECTING);
}

I don't understand what is the purpose of this line: 我不明白这行的目的是什么:

mConnectThread = null;

It seems this line is useless - anyway, just a few lines later mConnectThread is overwritten with new value. 看来这行没用-无论如何,仅几行之后,mConnectThread被新值覆盖。

It is safer to set mConnectThread to null earlier in this code, in case an exception is thrown before it has been set to a new value. 在此代码的前面,将mConnectThread设置为null mConnectThread安全,以防万一在将异常设置为新值之前引发了异常。 This way the old instance is available for garbage collection regardless of whether a new value is assigned. 这样,无论是否分配了新值,旧实例都可用于垃圾回收。

However, one could certainly argue for a better sequence of actions in this method. 但是,当然可以为这种方法中的一系列更好的动作辩护。 Generally you're right, there wouldn't be much point in setting it to null just before assigning a new value. 通常,您是对的,只是在分配新值之前将其设置为null没什么意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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