안드로이드 개발 질문/답변
(글 수 45,052)
아래 Thread에서 Line 39~41 부분이 이해가 안됩니다.
private class ConnectThread extends Thread { private final BluetoothSocket mmSocket; private final BluetoothDevice mmDevice; public ConnectThread(BluetoothDevice device) { mmDevice = device; BluetoothSocket tmp = null; // Get a BluetoothSocket for a connection with the // given BluetoothDevice try { tmp = device.createRfcommSocketToServiceRecord(MY_UUID); } catch (IOException e) { Log.e(TAG, "create() failed", e); } mmSocket = tmp; } public void run() { Log.i(TAG, "BEGIN mConnectThread"); setName("ConnectThread"); // Always cancel discovery because it will slow down a connection mAdapter.cancelDiscovery(); // Make a connection to the BluetoothSocket try { // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); } catch (IOException e) { connectionFailed(); // Close the socket try { mmSocket.close(); } catch (IOException e2) { Log.e(TAG, "unable to close() socket during connection failure", e2); } // Start the service over to restart listening mode BluetoothChatService.this.start(); return; } // Reset the ConnectThread because we're done synchronized (BluetoothChatService.this) { mConnectThread = null; } // Start the connected thread connected(mmSocket, mmDevice); } public void cancel() { try { mmSocket.close(); } catch (IOException e) { Log.e(TAG, "close() of connect socket failed", e); } } }
자기 자신을 null로 설정하는데, 왜 저렇게 하는지 궁금해 질문드립니다.
실행 중에 null로 설정한다는 게 제 생각으로는 이해가 잘 안되서요.
자세히 설명해 주시면 감사하겠습니다 : )
2010.08.24 14:31:05
BluetoothChatService 클래스의 멤버변수 mConnectThread 에 null 값을 할당한것이지,
ConnectThread 자기 자신에 null 값은 할당한 것이 아닙니다..
null 값은 넣은 이유는 mConnectThread 이 null 아니면
만약 동시에 connect와 connected가 발생 했다고 가정시 bluetoothchat 코드상으로 cancel() 을 호출하게 됩니다.
그렇게 되면 문제가 될부분이 mmSocket.close(); 가 호출되고 close된 상태의 socket이 connected(mmSocket, mmDevice); 로 호출될수 있습니다.
그럼 그다음에 null pointer exception 이 발생하는 것이지요~~
해당 코드가 없다고 항상 exception이 발생하는것 은 아니지만.. 저런 문제되는 부분은 예방해주어야 겠지요^^
따라서 다른 thread에서 null값 할당시 동기화를 맞쳐주고 멤버변수에 null 값을 넣음으로서 애초부터 exception 상황을 예방하는 것이지요~~
ConnectThread 자기 자신에 null 값은 할당한 것이 아닙니다..
null 값은 넣은 이유는 mConnectThread 이 null 아니면
만약 동시에 connect와 connected가 발생 했다고 가정시 bluetoothchat 코드상으로 cancel() 을 호출하게 됩니다.
그렇게 되면 문제가 될부분이 mmSocket.close(); 가 호출되고 close된 상태의 socket이 connected(mmSocket, mmDevice); 로 호출될수 있습니다.
그럼 그다음에 null pointer exception 이 발생하는 것이지요~~
해당 코드가 없다고 항상 exception이 발생하는것 은 아니지만.. 저런 문제되는 부분은 예방해주어야 겠지요^^
따라서 다른 thread에서 null값 할당시 동기화를 맞쳐주고 멤버변수에 null 값을 넣음으로서 애초부터 exception 상황을 예방하는 것이지요~~
ConnectThread
가 BluetoothChatService 안의 내부 클래스로 보이는데
BluetoothChatService 의 소스 내용이 보이지 않아 잘은 모르겠습니다만,
BluetoothChatService 안에서
mConnectThread 를 참조 하는 부분에도 synchronized 가 걸려있어 쓰레드가 종료 될때에는 또다른 쓰래드 참조가 일어 나지 않도록 하기 위해서 동기화 블럭을 걸어놓은것으로 보입니다.(예-
mConnectThread 가 null이 아닐때
mConnectThread 에 관련된 작업 수행 혹은
mConnectThread가 null일때 새로운 스래드 할당 과 같은)