netty学习笔记(一)

一、源码

1、new NioEventLoopGroup();

new NioEventLoopGroup(); // 点进去

new NioEventLoopGroup(); 不传参数,则采用默认线程数

private static final int DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
     super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
protected MultithreadEventExecutorGroup(int nThreads, Executor executor, EventExecutorChooserFactory chooserFactory, Object... args)  {
        this.terminatedChildren = new AtomicInteger();
        this.terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE);
        if (nThreads <= 0) {
            throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
        } else {
            if (executor == null) {
            	// ThreadPerTaskExecutor 继承了Excutor,实现命令模式
                executor = new ThreadPerTaskExecutor(this.newDefaultThreadFactory());
            }

            this.children = new EventExecutor[nThreads];

            int j;
            for(int i = 0; i < nThreads; ++i) {
                boolean success = false;
                boolean var18 = false;

                try {
                    var18 = true;
                    // 由 NioEventLoopGroup 实现,创建了 NioEventLoop 实例
                    this.children[i] = this.newChild((Executor)executor, args);
                    ...
        }
    }

2、ServerBootstrap serverBootstrap = new ServerBootstrap();

√ \color{#FF7D00}{√}   serverBootstrap.group(parentGroup, childGroup)

// 给 private volatile EventLoopGroup childGroup;以及父类中的 volatile EventLoopGroup group;赋值。
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) {
        super.group(parentGroup);
        if (this.childGroup != null) {
            throw new IllegalStateException("childGroup set already");
        } else {
            this.childGroup = (EventLoopGroup)ObjectUtil.checkNotNull(childGroup, "childGroup");
            return this;
        }
    }

√ \color{#FF7D00}{√}   serverBootstrap.channel(NioServerSocketChannel.class)

// 采用反射的方式,给 private volatile ChannelFactory<? extends C> channelFactory; 赋值
public B channel(Class<? extends C> channelClass) {
		// ReflectiveChannelFactory 和上面的 ThreadPerTaskExecutor 很像
        return this.channelFactory((io.netty.channel.ChannelFactory)(new ReflectiveChannelFactory((Class)ObjectUtil.checkNotNull(channelClass, "channelClass"))));
    }

√ \color{#FF7D00}{√}   serverBootstrap.bind(address).sync()

这里返回的ChannelFuture,JDK中也有一个Future,用于接受异步计算返回的结果。

但是JDK的future有一个缺点,调用get()方法将会阻塞主线程,这就违背了异步编程的初衷,Netty的ChannelFuture继承了Netty的Future并且改进了这一缺点。

Netty的Future继承了java.util.concurrent.Future<V>,在它的基础上做了扩展,可以通过监听器去判断是否有结果了(不会阻塞主线程)。

public interface Future<V> extends java.util.concurrent.Future<V> {
    boolean isSuccess();//是否计算成功
    boolean isCancellable();//可以被取消
    Throwable cause();//原因
    Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);//添加一个监听器
    Future<V> addListeners(GenericFutureListener<? extends Future<? super V>>... listeners);//添加多个监听器
    Future<V> removeListener(GenericFutureListener<? extends Future<? super V>> listener);//移除一个监听器
    Future<V> removeListeners(GenericFutureListener<? extends Future<? super V>>... listeners);//移除多个监听器
    Future<V> sync() throws InterruptedException;//等待结果返回
    Future<V> syncUninterruptibly();//等待结果返回,不能被中断
    Future<V> await() throws InterruptedException;//等待结果返回
    Future<V> awaitUninterruptibly();//等待结果返回,不能被中断
    boolean await(long timeout, TimeUnit unit) throws InterruptedException;
    boolean await(long timeoutMillis) throws InterruptedException;
    boolean awaitUninterruptibly(long timeout, TimeUnit unit);
    boolean awaitUninterruptibly(long timeoutMillis);
    V getNow();//立刻返回,没有计算完毕,返回null,需要配合isDone()方法判定是不是已经完成,因为runnable没有返回结果,
    //而callable有返回结果
    boolean cancel(boolean mayInterruptIfRunning);  //取消                                                          
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值