手写tomcat(三) 基于NIO的方式

在上一次的基础上做了改动,基于NIO的方式,使用了ThreadPoolExecutor线程池

public void acceptWait() {
        try {
            serverSocketChannel = ServerSocketChannel.open();
            //设置非阻塞
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            selector = Selector.open();
            serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //工作队列
        ArrayBlockingQueue<Runnable> workQueue  = new ArrayBlockingQueue<>(50);
        //线程池的基本大小,即在没有任务需要执行的时候线程池的大小
        int corePoolSize = 10;
        //线程池中允许的最大线程数
        int maximumPoolSize = 50;
        //空闲线程存活时间
        long keepAliveTime = 100L;
        //时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        //拒绝策略
        RejectedExecutionHandler rejectionStrategy = new ThreadPoolExecutor.DiscardOldestPolicy();

        ThreadPoolExecutor tpe = new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,keepAliveTime,unit,workQueue, Executors.defaultThreadFactory(),rejectionStrategy);


        while (true) {
            try {
                //阻塞1秒
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        SocketChannel socketChannel = serverSocketChannel.accept();
                        if(socketChannel != null){
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector,SelectionKey.OP_READ);
                        }
                    }else if(key.isReadable()){
                        SocketChannel channel = (SocketChannel) key.channel();
                        //处理过程中,先取消selector对应连接的注册,避免重复
                        key.cancel();
                        channel.configureBlocking(true);
                        tpe.execute(new RequestHandler(channel.socket()));
                    }
                    iterator.remove();
                }
                //
                selector.selectNow();
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值