Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java thread stuck with notify call

i'm stuck with this code, and i think that i'm missing something really important. when the thread is running i can add message to the vector but when it calls notify it seems that the getNextMessageFromQueue() keep to stay on the wait.

Am i locking the messages vars?

Thanks for your help.

My dispatcher class which send all messages to my clients :

private Vector<Message> messages = new Vector<Message>(); 

public synchronized void addMessage(Message message) {
    messages.add(message);
    notify(); 
}

private synchronized Message getNextMessageFromQueue() throws InterruptedException { 
    while (messages.size() < 1) {
        wait(); 
    }

    Message message = (Message) messages.get(0); 
    messages.removeElementAt(0);

    return message; 
}

private void sendMessageToAllClients(Message message) {     
    for (int i=0; i < clients.size(); i++) { 
        Client client = (Client) clients.get(i); 
        client.sendMessage(message); 
    } 
}

public void run() { 
    try { 
        while (true) { 
            Message message = getNextMessageFromQueue(); 
            sendMessageToAllClients(message); 
        } 
    } catch (InterruptedException ie) {
        ie.printStackTrace();
    } 
}

Here the client class :

private Socket socket;

private ObjectOutputStream out;
private ObjectInputStream in;

public Client(Socket s) throws IOException {
    socket = s;

    out = new ObjectOutputStream(socket.getOutputStream());
    in = new ObjectInputStream(socket.getInputStream());
}

public Socket getSocket() {
    return socket;
}

public void sendMessage(Message message) { 
    try {
        out.writeObject(message);
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }           
}

Here is the main call of addMessage :

Message message = new Message();
message.setMessage("Welcome to " + client.getSocket().getLocalAddress() + ":" + client.getSocket().getPort());

dispatcher.addMessage(message);
like image 849
user1952589 Avatar asked Mar 08 '26 09:03

user1952589


1 Answers

I think you have a mistake in line in = new ObjectInputStream(socket.getInputStream()); Remove it, if it is not necessary or rebuild in other way. Read this Java sockets: Program stops at socket.getInputStream() w/o error?

To understand if your inputData is empty use - socket.getInputStream().available(), it returns size of input bytes.

like image 175
Mary Ryllo Avatar answered Mar 10 '26 00:03

Mary Ryllo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!