Hey everyone, I'm writing a Java program that interfaces with a C program on my Linux server (it's a client/server chat program). Right now, I'm implementing a blocking feature for the input to block until the user presses "Enter" before sending the input to the server. To do this, I have two choices: a busy loop, and a mutex. The mutex is obviously the best alternative, but I'm running into an issue where sometimes the input just won't send to the server at *all*. With the busy loop, though, I just unset a flag and it works fine.
Busy loop:
String line = ""; // Block until we receive some input. while (!this.inputField.isReady()) { } line = this.inputField.getText(); this.writefp.write(line + "\n"); this.writefp.flush(); this.inputField.setReady(false);
So, all I need to do in the textfield (in a keylistener) is:
... public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { ready = true; setText(""); } } ...
So, yes, this works. My mutex solution isn't so lucky:
And the notifier:while (!this.inputField.isReady()) { synchronized(this.inputField.mutex) { try { this.inputField.mutex.wait(); } ... //redacted for simplicity } }
Maybe I'm misunderstanding a fundamental piece of Java's synchronization capabilities (this is much easier in C...). the mutex is just a standard Object, following online examples. Any help would be greatly appreciated.... ready = true; // This is in the TextField class. synchronized(this.mutex) { this.mutex.notify(); } setText(""); ...