Skip to content

Commit 26765c9

Browse files
committed
convert to NIO for #20 -- still unsure as to whether this is justified
1 parent a851a99 commit 26765c9

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/main/java/com/timgroup/statsd/NonBlockingStatsDClient.java

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
package com.timgroup.statsd;
22

3-
import java.net.DatagramPacket;
4-
import java.net.DatagramSocket;
53
import java.net.InetSocketAddress;
4+
import java.nio.ByteBuffer;
5+
import java.nio.channels.DatagramChannel;
66
import java.nio.charset.Charset;
7+
import java.text.NumberFormat;
78
import java.util.Locale;
89
import java.util.concurrent.ExecutorService;
910
import java.util.concurrent.Executors;
1011
import java.util.concurrent.ThreadFactory;
1112
import java.util.concurrent.TimeUnit;
12-
import java.text.NumberFormat;
1313

1414
/**
1515
* A simple StatsD client implementation facilitating metrics recording.
@@ -46,7 +46,7 @@ public final class NonBlockingStatsDClient extends ConvenienceMethodProvidingSta
4646
};
4747

4848
private final String prefix;
49-
private final DatagramSocket clientSocket;
49+
private final DatagramChannel clientSocket;
5050
private final StatsDClientErrorHandler handler;
5151

5252
private final ExecutorService executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@@ -109,7 +109,7 @@ public NonBlockingStatsDClient(String prefix, String hostname, int port, StatsDC
109109
this.handler = errorHandler;
110110

111111
try {
112-
this.clientSocket = new DatagramSocket();
112+
this.clientSocket = DatagramChannel.open();
113113
this.clientSocket.connect(new InetSocketAddress(hostname, port));
114114
} catch (Exception e) {
115115
throw new StatsDClientException("Failed to start StatsD client", e);
@@ -131,7 +131,12 @@ public void stop() {
131131
}
132132
finally {
133133
if (clientSocket != null) {
134-
clientSocket.close();
134+
try {
135+
clientSocket.close();
136+
}
137+
catch (Exception e) {
138+
handler.handle(e);
139+
}
135140
}
136141
}
137142
}
@@ -249,8 +254,7 @@ private void send(final String message) {
249254
private void blockingSend(String message) {
250255
try {
251256
final byte[] sendData = message.getBytes(STATS_D_ENCODING);
252-
final DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
253-
clientSocket.send(sendPacket);
257+
clientSocket.write(ByteBuffer.wrap(sendData));
254258
} catch (Exception e) {
255259
handler.handle(e);
256260
}

0 commit comments

Comments
 (0)