Skip to content

Commit

Permalink
Make socket reusable to avoid "Too many open files". Clean up constru…
Browse files Browse the repository at this point in the history
…ctors.
  • Loading branch information
devinfoley authored and kastner committed Apr 11, 2011
1 parent 306e7b7 commit e7d6b82
Showing 1 changed file with 10 additions and 19 deletions.
29 changes: 10 additions & 19 deletions StatsdClient.java
Expand Up @@ -28,8 +28,6 @@
* You know... the "Java way."
*/

package com.meetup.statsd;

import java.util.Random;
import java.io.IOException;
import java.net.DatagramPacket;
Expand All @@ -46,15 +44,17 @@ public class StatsdClient {

private InetAddress _host;
private int _port;

private DatagramSocket _sock;

public StatsdClient(String host, int port) throws UnknownHostException {
_host = InetAddress.getByName(host);
_port = port;
public StatsdClient(String host, int port) throws UnknownHostException, SocketException {
this(InetAddress.getByName(host), port);
}

public StatsdClient(InetAddress host, int port) {
public StatsdClient(InetAddress host, int port) throws SocketException {
_host = host;
_port = port;
_sock = new DatagramSocket();
}

public boolean timing(String key, int value) {
Expand Down Expand Up @@ -118,30 +118,21 @@ private boolean send(String stat, double sampleRate) {
}

private boolean send(double sampleRate, String... stats) {
DatagramSocket sock;

try {
sock = new DatagramSocket();
}
catch (SocketException e) {
log.error(e.getMessage());
return false;
}

boolean retval = false; // didn't send anything
if (sampleRate < 1.0) {
for (String stat : stats) {
if (RNG.nextDouble() <= sampleRate) {
stat = String.format("%s|@%f", stat, sampleRate);
if (doSend(sock, stat)) {
if (doSend(stat)) {
retval = true;
}
}
}
}
else {
for (String stat : stats) {
if (doSend(sock, stat)) {
if (doSend(stat)) {
retval = true;
}
}
Expand All @@ -150,10 +141,10 @@ private boolean send(double sampleRate, String... stats) {
return retval;
}

private boolean doSend(DatagramSocket sock, String stat) {
private boolean doSend(String stat) {
try {
byte[] data = stat.getBytes();
sock.send(new DatagramPacket(data, data.length, _host, _port));
_sock.send(new DatagramPacket(data, data.length, _host, _port));
return true;
}
catch (IOException e) {
Expand Down

0 comments on commit e7d6b82

Please sign in to comment.