view src/alice/daemon/OutboundTcpConnection.java @ 122:d5d9ca4cbe87 working fish-example-worked

fix memory leak!
author one
date Fri, 27 Jul 2012 02:04:45 +0900
parents b01fb5090e28
children 1044a79ce4ef
line wrap: on
line source

package alice.daemon;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.msgpack.MessagePack;

import alice.datasegment.Command;

public class OutboundTcpConnection extends Thread {
	
	public Connection connection;
	private static MessagePack MSGPACK = new MessagePack();
	
	public OutboundTcpConnection(Connection connection) {
		this.connection = connection;
	}
	
	public CommandMessage convert(Command cmd) {
		return new CommandMessage(cmd.type.id, cmd.index, cmd.seq, cmd.key, cmd.val);
	}
	
	/**
	 * pipeline thread for transmission
	 */
	public void run() {
		while (true) {
			try {
				Command cmd = connection.sendQueue.take();
				switch (cmd.type) {
				case CLOSE:
					connection.socket.close();
					return;
				case FINISH:
					System.exit(0);
					return;
				default:
					break;
				}
				CommandMessage cmdMsg = convert(cmd);
				ByteBuffer buffer = ByteBuffer.wrap(MSGPACK.write(cmdMsg));
				while (buffer.hasRemaining()) {
					connection.socket.getChannel().write(buffer);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}