I'm try to send data through socket in java, there are one server and multiple client, and I have a class called "Value":
public class Value<T extends Comparable<T>> implements Comparable<Value<T>> {
public T value;
public String result;
public Value(T value, String result) {
this.value = value;
this.result = result;
}
public int compareTo(Value<T> v) {
return value.compareTo(v.value);
}
}
In server, I have a large array of Value and a hashmap to record result frequency which were send to previous client, and I want to send that to each client, the code like this:
HashMap<String, Integer> frequency = new HashMap<>();
//assume all result are exists in the frequency's key
for (Client client: clients) {
for (String key : frequency.keySet()) {
client.bufferedWriter.write(key + ":" + frequency.get(key))
client.bufferedWriter.newLine();
}
for (int i = startIndex; i < endIndex; i++) {
client.bufferedWriter.write(values[i].value + "," + values[i].result)
client.bufferedWriter.newLine();
frequency.replace(values[i].result, frequency.get(values[i].result) + 1)
}
client.bufferedWriter.flush();
}
Each client will receive different values. For example, I have 2 client and 10 size of values, the first client will receive values from 0 to 4 , and the second client will receive frequency info of first client taken and values from 5 to 9. Maybe it couldn't make it parallel because it is sequential.
The code as above in my algorithm, it take me about 5 seconds. How can I write that data faster and do not use nio?