From 67530d6585b9e0d6c63d09cc23e8061b234fef98 Mon Sep 17 00:00:00 2001 From: Hugo Benichi Date: Wed, 13 Apr 2016 10:15:39 +0900 Subject: [PATCH] Add volatile qualifier to boolean variable DHCP receive thread was spinning on a boolean variable to know when to stop. That variable had no volatile qualifier, potentially preventing the thread from stopping at all. Without a volatile qualifier, the reads and writes in halt() could be reordered in such a way that the running thread is interrupted before mStopped is set t true. Also, the optimizer could decide to hoist mStopped in a register inside the running thread, preventing the loop from exiting. Change-Id: I5b30c1247808114f0e5b46e230978ee7ea18ab8e --- services/net/java/android/net/dhcp/DhcpClient.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/net/java/android/net/dhcp/DhcpClient.java b/services/net/java/android/net/dhcp/DhcpClient.java index 406dd56a62ba1..804fa0347bffc 100644 --- a/services/net/java/android/net/dhcp/DhcpClient.java +++ b/services/net/java/android/net/dhcp/DhcpClient.java @@ -336,17 +336,17 @@ public class DhcpClient extends StateMachine { class ReceiveThread extends Thread { private final byte[] mPacket = new byte[DhcpPacket.MAX_LENGTH]; - private boolean stopped = false; + private volatile boolean mStopped = false; public void halt() { - stopped = true; + mStopped = true; closeSockets(); // Interrupts the read() call the thread is blocked in. } @Override public void run() { if (DBG) Log.d(TAG, "Receive thread started"); - while (!stopped) { + while (!mStopped) { int length = 0; // Or compiler can't tell it's initialized if a parse error occurs. try { length = Os.read(mPacketSock, mPacket, 0, mPacket.length); @@ -355,7 +355,7 @@ public class DhcpClient extends StateMachine { if (DBG) Log.d(TAG, "Received packet: " + packet); sendMessage(CMD_RECEIVED_PACKET, packet); } catch (IOException|ErrnoException e) { - if (!stopped) { + if (!mStopped) { Log.e(TAG, "Read error", e); } DhcpClientEvent.logEvent(IpConnectivityEvent.IPCE_DHCP_RECV_ERROR,