I have this method to write messages to a socket:
public void sendMessage(byte[] msgB) {
try {
synchronized (writeLock) {
log.debug("Sending message (" + msgB.length + "): " + HexBytes.toHex(msgB));
ous.write(HEADER_MSG);
ous.writeInt(msgB.length);
ous.write(msgB);
ous.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Now a thread called Bob would like to close the socket at some undeterministic moment X, which means that there may still be threads waiting on writeLock to send their message, and there may even be one thread in the middle of writing it.
I can solve the latter by letting Bob acquire writeLock before closing the socket, but I could still lose messages that have not yet begun sending, because as far as I know synchronized is not fair, Bob could get the lock before some other thread that has been waiting longer.
What I need is that all calls made to sendMessage before X do their job normally, and calls made after X throw an error. How can I do this?
- Specifics: Bob is the thread reading from the socket’s input stream and X is when a “close” message is received on that stream.
I suppose I could replace the synchronized block with a ReentrantLock set to be fair.