Netty Future 小试牛刀


Listenable futures and event loops


Performing a task asynchronously - scheduling a task and getting notified on completion - is common, and should be easy.

When java.util.concurrent.Future appeared first, our excitement didn't last long.

We had to block to get notified on completion. In asynchronous programming, you specify what to do on completion rather than wait for the outcome.

io.netty.concurrent.Future is a subtype of JDK Future. It lets you add a listener which will be invoked by an event loop when the future is fulfilled.

io.netty.util.concurrent.EventExecutor is a single-threaded event loop that extends java.util.concurrent.ScheduledExecutorService.


You can build your own event loop or use it as a feature-rich task executor. Usually, you create multiple EventExecutors to take advantage of parallelism:

执行异步任务,执行一个轮询任务和当完成时任务时,获得一个通知是一个非常普通和应该非常容易事情。

当JDK中java.util.concurrent.Future 第一次出现时,我们的兴奋没有持续的太久。因为我们必须阻塞当前线程,才能当异步动作完成时获得通知。
在异步编程中,我们应该指定在异步操作完成时应该执行什么,而不是等待结果的到来。

在Netty中io.netty.concurrent.Future 是JDK Future的一个子类。可以Future 中添加Listener ,当Future异步动作完成时, Listener 可以被eventLoop 调用。

在Netty中io.netty.util.concurrent.EventExecutor 是一个单线程event loop. EventLoop是ScheduleExecutorService 的子类。


用户可以自定义自己的EventLoop 。通常,用户可以创建多个EventExecutors来充分利用CPU的并行。




netty Future 使用demo:

		EventExecutorGroup group = new DefaultEventExecutorGroup(4); 
		Future f =(Future) group.submit(new Callable() {

			public Integer call() throws Exception {
				Thread.sleep(1000);
				System.out.println("Sleep......");
				return new Integer(99);
			}
		});
		
		
		GenericFutureListener> listener =new GenericFutureListener>() {

			public void operationComplete(Future future) throws Exception {
				
				System.out.println("result:"+future.get());
			}
		};
		f.addListener(listener );

	



Comparison with Guava and JDK8



Because Netty tries to minimize its set of dependencies, some of its utility classes are similar to those in other popular libraries, such as Guava.





Netty focuses on providing the constructs required for:

  • Asynchronous programming
  • Low-level operations (a.k.a "mechanical sympathy") such as:
    • Off-heap access
    • Access to the proprietary intrinsic operations
    • Platform-dependent behaviors
java sometimes advances by adopting ideas that subsume constructs provided by Netty.For example, JDK 8 adds CompletableFuture which somewhat overlaps io.netty.util.concurrent.Future.


因为Netty尝试最小化依赖的数量,在Netty中的一些工具类和其他流行的类库比较类似。例如:Guava库。
Netty主要提供以下需求:   1、异步编程  2、低级操作 等。


Java语言有时候升级采用一些思想,比如:由Netty提供的Future模型。  JDK8 添加CompleteFuture 来覆盖io.netty.util.current.Future类。



参考链接:

http://netty.io/wiki/using-as-a-generic-library.html

你可能感兴趣的:(Netty Future 小试牛刀)