Reputation: 3
I have a class which holds a collection of references to workers threads that receive objects via TCP (1 per client).
I'm trying to make a method getMessage()
in my class which waits until any of the workers threads got a message and returns it.
What I got right now is a polling-system:
public Object getMessage() {
while (true) {
for (Worker w : workers.values())
if (w.msgNumber() != 0)
return w.getLastMsg();
Thread.sleep(100);
}
}
It works, but I don't think it's very scalable.
I know I can do a wait(timeout)
on each worker, but the problem stays the same.
Is there some kind of wait/notify mechanism which waits for multiple threads?
Upvotes: 0
Views: 802
Reputation: 2908
How about something like:
try {
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
while (true) {
System.out.println("Listening...");
// Waits for connection
new Thread(new ServerWorkerThread(srv.accept())).start();
}
} catch (IOException e) {
//handle
}
Upvotes: 0
Reputation: 25458
You could look at using a blocking queue for communications between threads. The worker thread would insert into the queue, while the getMessage()
function pulls a message from the queue.
Upvotes: 4