view final_main/src/RemoteDataGearManager.java @ 14:38f2c997bb93

update chap4
author akahori
date Tue, 19 Feb 2019 22:54:56 +0900
parents
children
line wrap: on
line source

public class RemoteDataGearManager extends DataGearManager{
    boolean connect = false;
    Object lock = new Object();

    public RemoteDataGearManager(final String dgmName, final String address, final int port, CodeGearManager cgm) {
        this.cgm = cgm;
        RemoteDataGearManager manager = this;
        new Thread("Connect-" + dgmName) {
            public void run() {
                do {
                    try {
                        SocketChannel sc = SocketChannel.open(new InetSocketAddress(address, port));
                        connection = new Connection(sc.socket(), cgm);
                        connection.name = dgmName;
                        connection.socket.setTcpNoDelay(true);
                        
                        // add lock
                        synchronized (lock){
                            connect = true;
                            lock.notify();
                        }
                    } catch (IOException e) {
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    }
                } while (!connect);
                IncomingTcpConnection in = new IncomingTcpConnection(connection);
                in.setManager(manager);
                in.setName(dgmName+"-IncomingTcp");
                in.setPriority(MAX_PRIORITY);
                in.start();
                OutboundTcpConnection out = new OutboundTcpConnection(connection);
                out.setName(dgmName + "-OutboundTcp");
                out.setPriority(MAX_PRIORITY);
                out.start();
            }
        }.start();

    }
    
     public void put(String key, Object data) {

        Command cm = new PutCommand(0, null, key, new DataGear(data));
        
        if(!connect) connectWait(); // add wait

        connection.write(cm);
   }
    
    // add method
    public void connectWait(){
        synchronized (lock){
            while(!connect){
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
}