Java NIO 2 Présentation pour la sortie de Java 7 chez Xebia. Par Julien Buret et Séven Le Mesle
Text of Java Nio 2
1. Java 7 Asynchronous I/O (NIO2) Julien Buret Sven Le
Meslevendredi 29 juillet 2011
2. Asynchronous I/O API Comparaison avec les autres API I/O
Socket SocketChannel AsyncSocketC hannel Java 1.0 Java 1.4 Java 1.7
Synchrone Synchone Asynchrone Bloquant Non bloquant Non bloquant
Reactor pattern Proactor pattern Noticationvendredi 29 juillet
2011
3. Asynchronous I/O API Comparaison avec les autres API I/O
FileOutputStream FileChannel AsynchronousFileChannel
FileInputStream OutputStream SocketChannel
AsynchronousSocketChannel InputStream OutputStream
ServerSocketChannel AsynchronousServerSocketChannel InputStream
Java 1.0 Java 1.4 Java 1.7vendredi 29 juillet 2011
4. Asynchronous I/O API Crer un channel
AsynchronousChannelGroup channelGroup =
AsynchronousChannelGroup.withFixedThreadPool(4, threadFactory);
AsynchronousServerSocketChannel socketChannel =
AsynchronousServerSocketChannel.open (channelGroup);
socketChannel.bind(new InetSocketAddress(8080)); Future resAccept =
socketChannel.accept(); Future res =
resAccept.get().read(ByteBuffer.allocate(512));vendredi 29 juillet
2011
5. Asynchronous I/O API Concept : Future Future result =
channel.read(byteBuffer); Retourne un Future avec le nombre doctet
lue (ou crit) result.get(); Attend la n de lopration I/O
result.get(5, TimeUnit.SECONDS); Attend avec un timout
result.isDone(); Verie si lappel est terminvendredi 29 juillet
2011
6. Asynchronous I/O API Concept : CompletionHandler
channelToClient.read(buffer, counter, new CompletionHandler() {
public void completed(final Integer result, final AtomicInteger
counter){ handlerThreadPool.submit(new Runnable() { public void
run() { readComplete(result, counter, buffer, channelToClient); }
}); } public void failed(Throwable exc, AtomicInteger counter) {
logger.error("Client {} failed to read", counter, exc); }
});vendredi 29 juillet 2011
7. Threading model AsynchronousChannelGroup Encapsule le pool
de thread, la le dattente et les autres ressources partages par les
sockets 2 implmentations Fixed thread pool Cached thread pool (ou
thread pool fournit)vendredi 29 juillet 2011
8. Threading model Fixed thread pool CompletionHandler I/O
internal Thread Thread Threadvendredi 29 juillet 2011
9. Threading model Cached thread pool CompletionHandler Thread
Thread Thread Cached Thread pool I/O internal Thread Thread
Internal Thread pool 1 ou sun.nio.ch.internalThreadPoolSizevendredi
29 juillet 2011
10. Threading model FixedThreadPool CachedThreadPool ou
ThreadPool fournit Thread partag entre I/O et callback Un pool de
thread pour lI/O et un autre Eviter la contention pour les callback
dans les callback Attention au context switchvendredi 29 juillet
2011
11. Bench Sur une VM 2vCPU (client et serveur) 4000 req/s
(50Ko/req et 50Ko/resp) 200 Mo/s (Reu et mis)vendredi 29 juillet
2011
13. Multicast non bloquant while (true) { selector.select();
Iterator it = selector.selectedKeys().iterator(); while
(it.hasNext()) { SelectionKey selKey = (SelectionKey) it.next();
it.remove(); if (selKey.isValid() && selKey.isReadable()) {
DatagramChannel sChannel = (DatagramChannel) selKey.channel(); } if
(selKey.isValid() && selKey.isWritable()) { DatagramChannel
sChannel = (DatagramChannel) selKey.channel(); } } }vendredi 29
juillet 2011
14. Le reste Mise jour des API SocketChannel bind(SocketAdress
local) setOption(SocketOption name, T Value) Support de SCTP
(Protocole de transport rseau) IPV6 sous Windows Support de SDP
sous Solaris (protocole RMDA utilis par Inniband)vendredi 29
juillet 2011
15. File extension Traitement Asynchrone Droits POSIX / ACL NFS
/ DOS / ... Liens symboliques et vrous Systme de chier et
partitions Supervision dactivit sur rpertoires et chiers Parcours
de rpertoire Mthodes utilitairesvendredi 29 juillet 2011
16. java.nio.Path = java.io.File le.toPath() - path.toFile()
chemin systme du chier Path p = Paths.get(/home/user/.myApp);
Iterator it = p.iterator(); // elements
p.relativize(Paths.get(/home/john)); // ../john p.normalize(); //
/home/john/../user = /home/user p.startsWith(/home);vendredi 29
juillet 2011
17. AsynchronousFileChannel Traitement asynchrone non bloquant
Chaque read/write donne la position dans le chier Accde a plusieurs
parties du chier en parallle Threadsafe Supporte les Locks Options
dnies sur open(...)vendredi 29 juillet 2011
18. AsynchronousFileChannel AsynchronousFileChannel afc =
AsynchronousFileChannel.open(path, StandardOpenOption.CREATE);
FileLock lock = afc.lock().get(); afc.write(buffer, 0l).get(); //
Buffer wrote to le lock.close(); afc.close();vendredi 29 juillet
2011
19. Files operations Files fournit des utilitaires (guava /
commons-io) copy / move / delete /... read* / write / newReader* /
newWriter* temp dirs / symlinks / walkFileTree Et les accs systmes
set or get : owner / attribute / posixFilePermissions FileSystem /
FileStorevendredi 29 juillet 2011
20. FileAttributes Lecture et modication des atributs du chier
BasicFileAttributes, PosixFileAttributes, Dos, ... Path p =
Paths.get(/home/user/.myApp); BasicFileAttributes attr =
Files.readAttributes(le,BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModiedTime: " + attr.lastModiedTime());
System.out.println("isDirectory: " + attr.isDirectory());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size()); Set perms =
PosixFilePermissions.fromString("rw-------"); FileAttribute>
attr = PosixFilePermissions.asFileAttribute(perms);
Files.setPosixFilePermissions(le, perms);vendredi 29 juillet
2011
21. WatchService Comme un Selector pour les Paths WatchKey k =
register(path, event, ...); WatchEvent evt = k.pollEvents(); Reset
key Boucle inni et Threading la charge du dveloppeurvendredi 29
juillet 2011
22. WatchService Path p = Paths.get(/home/user/.myApp);
WatchService watcher = FileSystems.getDefault().newWatchService();
WatchKey key = p.register(watcher, ENTRY_CREATE, ENTRY_DELETE,
ENTRY_MODIFY); for (;;) { key = watcher.take(); for (WatchEvent
event: key.pollEvents()) { WatchEvent.Kind kind = event.kind();
WatchEvent ev = (WatchEvent)event; Path lename = ev.context();
//.... } boolean valid = key.reset(); if (!valid) { break; }
}vendredi 29 juillet 2011
23. DirectoryStream Autorise le forEach() sur les entres dun
rpertoire Glob pattern (*.java) RegExp Filtre implment
DirectoryStream ds = Files.newDirectoryStream(dir, *.java);
for(Path p : ds){ // ... }vendredi 29 juillet 2011
24. FileVisitor Files.walkFileTree parcours larborescence
utilise un FileVisitor Dnit des options (FOLLOW_LINKS, ... )
FileVisitor est invoqu pour chaque entre Permet de modier le
parcours Fourni des callbacks pre/post visit File /
Directoryvendredi 29 juillet 2011
25. FileVisitor Path start = ... Files.walkFileTree(start, new
SimpleFileVisitor() { @Override public FileVisitResult
visitFile(Path le, BasicFileAttributes attrs) throws IOException {
Files.delete(le); return FileVisitResult.CONTINUE; } @Override
public FileVisitResult postVisitDirectory(Path dir, IOException e)
throws IOException { if (e == null) { Files.delete(dir); return
FileVisitResult.CONTINUE; } else { // directory iteration failed
throw e; } } });vendredi 29 juillet 2011