Reputation: 77
This is a Thread with a Socket-connection.
The Server sends random int numbers to this socket (every 10 ms). The Problem is, that after a while the are huge lags of receiving the data and LogCat prints a lot of "GC_CONCURRENT freed" messages.
public class TcpSocketThread extends Thread {
Context context;
String ip;
int port;
public TcpSocketThread(Context con, String ip, int port) {
context = con;
this.ip = ip;
this.port = port;
}
@Override
public void run() {
Socket client;
try {
client = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(
client.getInputStream()));
String msg;
while (true) {
if (in.ready()) {
msg = in.readLine();
Intent intent = new Intent(BLUETOOTH_DATA);
intent.putExtra(BLUETOOTH_DATA_STRING, msg);
context.sendBroadcast(intent);
Log.v("Tcp-Socket-Thread", "msg: " + msg);
}
}
} catch (UnknownHostException e) {
Log.v("client", "unknown host" + e);
} catch (IOException e) {
Log.v("client", "No I/O" + e);
}
}
}
Upvotes: 0
Views: 522
Reputation: 719426
You should not repeatedly poll ready()
to test whether there is data to be read. Just call readLine()
. It will block the thread until either there is data to be read or the connection is closed.
But I don't think that is what is generating the garbage. I suspect that that is something to do with what you are doing with the lines that you are reading. I understand that using intents involves Java object streams, and they are fairly heavy-weight in terms of the memory they use in the serialization and deserialization processes. And it appears that you could be doing the deserialization in multiple places ... depending on what listens for the broadcasted intents.
Upvotes: 0
Reputation: 883
You should not repeatedly poll ready() to test whether there is data to be read. Just call readLine(). It will block the thread until there is data to be read or the connection is closed.
is a good suggestion for the read block, but you are creating new Intent every time you process your data, can you just reuse this object? This is the part causing your GC to go crazy.
Hope this helps and enjoy your work.
Upvotes: 1