Skip to content

Commit 9dbef97

Browse files
nickkralAndroid (Google) Code Review
authored andcommitted
Merge "Avoid leaking sockets." into gingerbread
2 parents e4a5951 + 2ed20f8 commit 9dbef97

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

core/java/android/net/SntpClient.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,9 @@ public class SntpClient
7272
* @return true if the transaction was successful.
7373
*/
7474
public boolean requestTime(String host, int timeout) {
75+
DatagramSocket socket = null;
7576
try {
76-
DatagramSocket socket = new DatagramSocket();
77+
socket = new DatagramSocket();
7778
socket.setSoTimeout(timeout);
7879
InetAddress address = InetAddress.getByName(host);
7980
byte[] buffer = new byte[NTP_PACKET_SIZE];
@@ -96,7 +97,6 @@ public boolean requestTime(String host, int timeout) {
9697
socket.receive(response);
9798
long responseTicks = SystemClock.elapsedRealtime();
9899
long responseTime = requestTime + (responseTicks - requestTicks);
99-
socket.close();
100100

101101
// extract the results
102102
long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
@@ -123,6 +123,10 @@ public boolean requestTime(String host, int timeout) {
123123
} catch (Exception e) {
124124
if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
125125
return false;
126+
} finally {
127+
if (socket != null) {
128+
socket.close();
129+
}
126130
}
127131

128132
return true;

0 commit comments

Comments
 (0)