자바네트워크 제12주
셀렉터
제15장 셀렉터
• 필요성
• 셀렉터의개요
• 기졲의 네트워크 프로그래밍 모델
• 비블록킹 모델
• SelectableChannel
• SelectionKey
• Selector
• 비블록킹 서버 만들기
• 논의
필요성
• 멀티스레드 서버는 성능에 한계가 있음
• Thread context switching is expensive
• 셀렉터를 이용한 멀티플렉스 모델이 효율적임
셀렉터의 개요
기졲의 네트워크프로그래밍 모델
Socket s = serverSocket.accept();
InputStream in =s.getInputStream();
OutputStream out = s.getOutputStream();
in.read();
out.write();
s.close();
멀티스레드 기반 서버
Socket s = serverSocket.accept();
InputStream in =s.getInputStream();
OutputStream out = s.getOutputStream();
in.read();
out.write();
s.close();
Service service = new Service(s);
service.start();
Service Thread
멀티스레드 기반의 단점
• 많은 스레드 생성에 따른 스레드 컨텍스트 스위치 부하
• 스레드 자체가 CPU와 고유 스택을 갖는 데 따른 컴퓨터 리 소스 부하
• 클라이언트의 빈번한 접속과 종료에 따라 많은 가비지가 생성되는 문제점
• 클라이언트가 접속할 때마다 매번 스레드를 새로 생성하는 부담
• 서버의 메모리가 부족하여 OutOfMemoryException 이 발생 할 가능성
비블록킹 모델
• Selector
• SelectableChannel
• SelectionKey
• 블록킹 모드의 자료 읽기
in.read();
Do something
비블록킹 모드 동작 과정
Selector 생성
Selector에
SelectableChannel 등록
Selector로부터 준비된 SelectionKey 검색 SelectionKey로 부터
Channel 작업
SelectableChannel
Methods
이벤트 종류
서버소켓의 등록
일반소켓채널 등록
가능한 이벤트
• ServerSocketChannel
• OP_ACCEPT
• SocketChannel
• OP_CONNECT, OP_READ, OP_WRITE
• DatagramChannel
• OP_READ, OP_WRITE
동작
Selector
SelectionKey Write
SelectionKey Read
SelectionKey Read & Write
SelectionKey
Methods
Methods
Selector
Registered Key Set
Selected Key Set
Cancelled Key Set
Methods
Selection 동작
Registered Key Set
Selected Key Set Cancelled Key Set
비블록킹 채팅 서버만들기
• SimpleChatServer
• SimpleChatClient