* @throws MistException
* The session is closed or sending error occurs
*/
public boolean writeMessage(MessageBlock msg, int timeout) throws MistException {
if(error)
throw new MistException("session error, close and recreate it");
if(onClose)
throw new MistException("session closed");
waitingThread = Thread.currentThread();
long startTs = System.currentTimeMillis();
Acker acker = new Acker();
if(timeout > 0) {
try {
if(!localQueue.offer(new MessagePair(msg, acker), timeout, TimeUnit.MILLISECONDS))
return false;
long timeElapsed = (System.currentTimeMillis() - startTs);
long timeLeft = timeout - timeElapsed;
if(timeLeft <= 0)
return false;
synchronized(acker) {
// if it is already acked, return true, or wait to be acked
if(acker.acked())
return true;
acker.wait(timeLeft);
return acker.acked();
}
}
catch(InterruptedException e) {
if(errorStr == null)
throw new MistException("connection to MIST is broken!");
else
throw new MistException(errorStr);
}
}
else {
try {
localQueue.put(new MessagePair(msg, acker));
synchronized(acker) {
if(acker.acked())
return true;
acker.wait();
return acker.acked();
}
}
catch(InterruptedException e) {
if(errorStr == null)
throw new MistException("connection to MIST is broken!");
else
throw new MistException(errorStr);
}
}
}