一古程、線程池
1喊崖、基本線程池
描述:
1)從池中的空閑線程列表中選擇一個Thread,并且指派它去運行一個已提交的任務(一個Runnable的實現(xiàn))荤懂;
2)當任務完成時,將該Thread返回給該列表呜达,使其可被重用
問題:
雖然池化和重用線程相對于簡單地為每個任務都創(chuàng)建和銷毀線程都是一種進步粟耻,但是它并不能消除由上下文切換帶來的開銷,其將隨著數(shù)量的增加很快變得明顯霜威,并且在高負載下越發(fā)嚴重册烈。
2婿禽、Netty線程模型
Reactor模型:
維基百科解釋:The reactor design pattern is an event handling pattern for handling service requests delivered concurrently by one or more inputs. The service handler then demultiplexes the incoming requests and dispatches them synchronously to associated request handlers.
Netty線程模型:
1.Selector
2.EventLoopGroup/EventLoop
3.ChannelPipeline
Selector
selector是java nio提供的SelectableChannel多路復用器扭倾,它維護這三個SelectionKey集合,負責配合selector操作將就緒的IO事件分離出來膛壹,表現(xiàn)為SelectionKey.在Netty線程模型唉堪,Selector充當著多路復用器的作用误窖,而對于SelectionKey理解為Reactor中的資源。
EventLoop/EventLoopGroup
BossEventLoopGroup通常是一個單線程的EventLoop,EventLoop維護著一個注冊了ServerSocketChannel的Selector實例培漏,BossEventLoop不斷輪詢Selector將連接事件分離出來沧侥,通常是OP_ACCEPT事件,然后將accept得到的socketChannel交給WorkerEventLoopGroup,WorkerEventLoopGroup會由next選擇其中一個EventLoopGroup來將這個SocketChannel注冊到其維護的Selector并對其后續(xù)的IO事件進行處理暂题。