자바네트워크 제9주
NIO 개요
제12장 NIO 개요
• 필요성
• 자바IO는 느리다?
• 블록킹 자바 IO
• IO 향상을 위한 운영체제 수준의 기술
• 자바의 새로운 변화
• 논의
필요성
• 자바 IO는 native 보다 상대적으로 느렸다.
• Nonblocking IO 기능
자바 IO는 느리다?
• 자바가 느린 부분은 swing과 IO 이다.
• 사용이 간편하다.
블록킹 자바 IO
• IO의 흐름
버퍼 ㅍ 프로세스 유저영역
버퍼 버퍼
커널영역
read() DMA
디스크 하드웨어
IO 향상을 위한 운영체제수준 의 기술
• Buffer
• One byte read
• Using buffer
• Full buffer(enough size)
• Scatter/Gather
버퍼
버퍼 버퍼
버퍼
가상 메모리(Virtual Memory)
버퍼 ㅍ 프로세스 유저영역
버퍼 버퍼
커널영역
read() DMA
디스크 하드웨어
메모리 맵 파일
버퍼 ㅍ 프로세스 유저영역
버퍼 버퍼
커널영역
read() 페이지 매핑
디스크 하드웨어
파일 락
• Shared lock
• Exclusive lock
자바의 새로운 변화
• 자바의 포인터 버퍼 도입
• DiectByteBuffer
• 네이티브 IO서비스를 제공해주는 채널 도입
• 셀렉터 도입
Contents
• An Example Client
• An Example Server
• Buffers
• Channels
• Readiness Selection
Introduction
• Network communication is very slow
• Use Buffering and Threads to overcome
• Channel : an open connection to hardware device, file, network, program component
• RFC864 Chargen protocol
Basic operation
• Channel is a connection to any type of hardware
• It can be operated as blocking or non-blocking mode
An Example Client
• Open a SocketChannel
• Read data using ByteBuffer (blocking mode)
An Example Client
• Read data using ByteBuffer (non-blocking mode)
Sample output
An Example Server
Selector
Server Channel(OP_ACCEPT)
Client Channel(OP_READ)
Client Channel(OP_READ)
Channel Pool
register
OP_CONNECT OP_READ
select
watch
Server Algorithm
Select prepared Channel
Do appropriate job for ready channels start
Yes Prepare character set
end Prepare ServerChannel
Prepare Selector Register ServerChannel
to Selector
Is
IOException No
Prepare Characterset
Prepeare channel and selector
Selection loop
For accept operation
For write operation
Buffers
• Stream is stream based
• Channel is block based using buffer
• ByteBuffer, CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer, DoubleBuffer
• Network program uses ByteBuffer
Buffers
• clear() : remove all data
• rewind() : reset the position to be zero
• flip() : set limit as the current position and reset the current position to be zero
• hasRemaining() : return true if there is some data between current position and the limit
• allocate() : generate fixed size buffer
• put(), get() : fill or get data buffer
• order() : LITTLE_ENDIAN, BIG_ENDIAN
ViewBuffer
• asShortBuffer()
• asCharBuffer()
• asIntBuffer()
• asLongBuffer()
• asFloatBuffer()
• asDoubleBuffer()
Buffer compactification
• Move remaining data to front part of the buffer
• compact()
Buffer duplication
• Can be used to send the same content to more than two channels
• duplicate()
• slice()
• mark()
• reset()