/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.net.test;

import java.io.IOException;
import java.io.OutputStream;
import java.rmi.server.RMISocketFactory;
import java.util.Random;

import edu.emory.mathcs.util.net.Connection;
import edu.emory.mathcs.util.net.ConnectionPool;

final class Test {
    private static final ConnectionPool POOL =
        new ConnectionPool(
            "localhost",
            9090,
            RMISocketFactory.getDefaultSocketFactory(),
            5000,
            5);
    private static final Random RANDOM = new Random();

    static class Work implements Runnable {
        private final Connection conn;

        Work(Connection conn) {
            this.conn = conn;
        }

        public void run() {
            long end = System.currentTimeMillis() + 1000 + RANDOM.nextInt(5000);
            try {
                OutputStream os = conn.getSocket().getOutputStream();
                do {
                    os.write('a');
                } while (System.currentTimeMillis() < end);
            } catch (IOException e) {
                e.printStackTrace();
                conn.close();
            }
            conn.returnToPool();
        }
    }

    public static void main(String[] args)
        throws IOException, InterruptedException {
        do {
            Connection conn = POOL.getConnection();
            new Thread(new Work(conn)).start();
            Thread.sleep(4000 + RANDOM.nextInt(2000));
        } while (true);
    }
}
