Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JAVA NIO

858 views

Published on

2009년 11월 05일
카페 세미나 자료

Published in: Technology
  • Be the first to comment

JAVA NIO

  1. 1. 문서타이틀 영역 | 2007. 02 . 23 기획 : 마케팅 팀 이 정 민 2009. 11 . 05 HANOSEOK JAVA NIO
  2. 2. Java IO is slow … ? - Array Copy - Stream Base IO - Blocking IO
  3. 3. KernelProcess (JVM) Disk Controller BufferBuffer DISK Java IO read() arrayCopy() DMA SLOW - Using CPU to Buffer - Thread Blocking - Array Gabage Collection
  4. 4. Stream Base IO STREAM....sr.#I..value[.. ze.Parent..B.ur.. - Serialization - One-way Communication
  5. 5. Blocking IO ServerSocket server = new ServerSocket(8080); Socket sock = server.accept(); InputStream in = sock.getInputStream(); len = in.read(buf); … Blocking Blocking
  6. 6. Java NIO New IO Non-Blocking IO
  7. 7. Java NIO is fast … ? Array Copy -> Direct Buffer Stream Base IO -> Channel Base IO Blocking IO -> Non-Blocking IO
  8. 8. KernelProcess (JVM) Disk Controller Buffer DISK Java NIO – Direct Buffer read() DMA Direct - Not use CPU to Buffer - Thread Non-Blocking - Reference Gabage Collection
  9. 9. Java NIO – Channel - Scatter/Gather - Two-way Communication TITLE : G ... One Day. ... ……………… Therefore ... T I T L E … O n e D … T h e r e … CHANNEL
  10. 10. Non-blocking IO ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(port)); Ssc.configureBlocking(false); while(true){ SocketChannel sc = ssc.accept(); if(null != sc){ sc.read(buf); … } } Non-blocking Non-blocking
  11. 11. Buffer CharSet Channel Selecter
  12. 12. Buffer Direct Buffer Handling, Pointer, Endian CharSet Character Encoding Channel Scattering/Gathering, Memory Mapped File, File Locking, Non-blocking IO Selector select
  13. 13. Buffer Buffer MappedByteBuffer CharBuffer IntBuffer LongBuffer DoubleBuffer FloatBuffer ByteBuffer ShortBuffer Direct or Non-Direct Buffer Only Direct Buffer
  14. 14. H E L L O W Buffer Pointer position capacitymark limit 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 (-1) (0) (capacity) (max(buffer)) put((byte)‘O’) reset() get(3) mark <= position <= limit <= capacity
  15. 15. -clear() : All pointer default setting -reset() : Move position to mark -rewind() : Set position 0 -flip() : Move limit to position , position to 0, mark to -1 Buffer Method
  16. 16. Direct VS Non-Direct Buffer ByteBuffer buf = ByteBuffer.allocate(10); ByteBuffer directBuf = ByteBuffer.allocateDirect(10); CharBuffer chBuf = ByteBuffer.allocateDirect(10).asCharBuffer(); // 5 Characters IntBuffer intBuf = ByteBuffer.allocateDirect(10).asIntBuffer(); // 2 Integers
  17. 17. Direct VS Non-Direct Buffer Non Direct Buffer Java Byte Array Direct Buffer Java Byte Array ByteBuffer buf = ByteBuffer.wrap(new byte[10]); byte [] b = ByteBuffer.allocate(10).array();
  18. 18. Direct VS Non-Direct Buffer Direct Buffer Non-Direct Buffer Create Time Long Short IO Time Short Long GC Time Long Short
  19. 19. Channels
  20. 20. Channels File Channel Socket Channel
  21. 21. File Channel - Open FileInputStream().getChannel(); // Read Only FileOutputStream().getChannel(); // Write Only RandomAccessFile ().getChannel(); // Read & Write
  22. 22. File Channel - Use RandomAccessFile raf = new RandomAccessFile(“Hello.txt”, "rw”); FileChannel fc = raf.getChannel(); ByteBuffer head = ByteBuffer.allocateDirect(5); ByteBuffer tail = ByteBuffer.allocateDirect(5); fc.read(head); raf.seek(6); fc.read(tail); fc.position(0); head.flip(); tail.flip(); fc.write(tail); raf.seek(6); fc.write(head); W O R L D H E L L O ! H E L L O W O R L D ! Scattering Gathering CHANNEL CHANNEL HELLO WORLDhead tail
  23. 23. File Channel - Use RandomAccessFile raf = new RandomAccessFile(“Hello.txt”, "rw”); FileChannel fc = raf.getChannel(); ByteBuffer head = ByteBuffer.allocateDirect(5); ByteBuffer tail = ByteBuffer.allocateDirect(5); fc.read(head); raf.seek(6); fc.read(tail); fc.position(0); head.flip(); tail.flip(); fc.write(tail); raf.seek(6); fc.write(head); Sharing File Discrptor
  24. 24. Memory Mapped File W o r l d Hello World! Hello New IO!! MappedByteBuffer We are the World
  25. 25. Memory Mapped File RandomAccessFile raf = new RandomAccessFile(“Hello.txt”, "rw”); FileChannel fc = raf.getChannel(); MappedByteBuffer world = raf.getChannel().map(MapMode.READ_ONLY, 6,10); for(int i = 0; i<5; i++){ System.out.print(world.get()); } changeFileContent(“Hello.txt”); world.flip(); for(int i = 0; i<5; i++){ System.out.print(world.get()); } W O R L D HELLO OSHAN! O S H A N
  26. 26. MapMode.READ_ONLY MapMode.READ_WRITE MapMode.PRIVATE MapMode
  27. 27. File Locking public abstract FileLock lock(long position, long size, boolean shared); public abstract FileLock tryLock(long position, long size, boolean shared); OverlappingFileLockException Shared Lock Exclusive Lock
  28. 28. File Locking RandomAccessFile raf = new RandomAccessFile(“Hello.txt”, "rw”); FileChannel fc = raf.getChannel(); FileLock lock = fc.lock(0, 10, false); synchronized(lock){ … } MyThread t = new MyThread(lock); class MyThread extends Thread{ void run(){ if(lock.isShared()){ … } } }
  29. 29. Before Socket Channel … Asynchronous IO - Multi Thread - Polling - Select - Signal / Callback
  30. 30. Polling 5분에 한번씩 확인……… 하라는 농구는 안하고… 브아걸 앨범이 올 때가 됐는데…
  31. 31. Select 여러 개 등록 후 확인 왔구나@.,@
  32. 32. Signal / Callback 결과를 Signal 이나 Callback 호출을 이용하여 알려줌 olleh!~~~
  33. 33. Blocking IO ServerSocket server = new ServerSocket(8080); Socket sock = server.accept(); InputStream in = sock.getInputStream(); len = in.read(buf); … Blocking Blocking
  34. 34. Multi Thread IO ServerSocket server = new ServerSocket(8080); while(true){ Socket sock = server.accept(); new ServerProcess (sock).start(); } class ServerProcess extends Thread{ public void run(){ InputStream in = sock.getInputStream(); len = in.read(buf); … } }
  35. 35. Multi Thread Problem Gabage Collection Thread Context Switch Overhead Real-time (Chat) Out Of Memory
  36. 36. Polling public class ServerAcceptor extends Thread{ public void run(){ Socket sock = server.accept(); socketList.add(socket); } } public class ServerProcess extends Thread{ while(true){ for(Socket sock : socketList){ InputStream in = sock.getInputStream(); len = in.read(buf); … } } }
  37. 37. Polling Problem - Waiting Hi Hi
  38. 38. NIO Socket Channel public SelectableChannel configureBlocking(boolean block) throws IOException ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(port)); ssc.configureBlocking(false); while(true){ SocketChannel sc = ssc.accept(); if(null != sc){ sc.read(buf); … } } Non-blocking Non-blocking
  39. 39. Select Hi Hi
  40. 40. ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.socket().bind(new InetSocketAddress(port)); ssc.configureBlocking(false); Selector selector = Selector.open(); ssc.register(selector, SelectionKey.OP_ACCEPT); while(true){ selector.select(); Set<SelectionKey> keyset = selector.selectedKeys(); for (SelectionKey key : keyset) { SocketChannel sc = (ServerSocketChannel) key.channel ().accpept(); sc.register(selector, SelectionKey.OP_READ); … } } NIO Selector Non-blocking select : wait
  41. 41. SelctionKey.OP_ACCEPT SelctionKey.OP_CONNECT SelctionKey.OP_READ SelctionKey.OP_WRITE SelectionKey
  42. 42. 감사합니다

×