protected void onWrite(SelectionKey key) {
boolean isLockedByMe = false;
if (currentMessage.get() == null) {
// get next message
WriteMessage nextMessage = writeQueue.peek();
if (nextMessage != null && writeLock.tryLock()) {
if (!writeQueue.isEmpty()
&& currentMessage.compareAndSet(null, nextMessage)) {
writeQueue.remove();
}
} else {
return;
}
} else if (!writeLock.tryLock()) {
return;
}
updateTimeStamp();
isLockedByMe = true;
WriteMessage currentMessage = null;
// make read/write fail, write/read=3/2
final long maxWritten = readBuffer.capacity() + readBuffer.capacity() >>> 1;
try {
long written = 0;
while (this.currentMessage.get() != null) {
currentMessage = this.currentMessage.get();
currentMessage = preprocessWriteMessage(currentMessage);
this.currentMessage.set(currentMessage);
long before = this.currentMessage.get().getWriteBuffer()
.remaining();
Object writeResult = null;
if (written < maxWritten) {
writeResult = writeToChannel(currentMessage);
written += this.currentMessage.get().getWriteBuffer()
.remaining()
- before;
} else {
// wait for next time to write
}
// write complete
if (writeResult != null) {
this.currentMessage.set(writeQueue.poll());
handler.onMessageSent(this, currentMessage.getMessage());
// try to get next message
if (this.currentMessage.get() == null) {
if (isLockedByMe) {
isLockedByMe = false;
writeLock.unlock();
}
// get next message
WriteMessage nextMessage = writeQueue.peek();
if (nextMessage != null && writeLock.tryLock()) {
isLockedByMe = true;
if (!writeQueue.isEmpty()
&& this.currentMessage.compareAndSet(null,
nextMessage)) {