Krisprolls
Krisprolls

Reputation: 3

Java: Wait/Notify on multiple threads

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

Answers (2)

Jeremy
Jeremy

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

Kenster
Kenster

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

Related Questions