SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Java 7
           Asynchronous I/O (NIO2)

                               Julien Buret
                            Séven Le Mesle



vendredi 29 juillet 2011
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
                                    Notification
vendredi 29 juillet 2011
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.7

vendredi 29 juillet 2011
Asynchronous I/O API
           Créer un channel

      AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(4,
      threadFactory);
      AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open
      (channelGroup);
      socketChannel.bind(new InetSocketAddress(8080));
      Future<AsynchronousSocketChannel> resAccept = socketChannel.accept();
      Future<Integer> res = resAccept.get().read(ByteBuffer.allocate(512));




vendredi 29 juillet 2011
Asynchronous I/O API
           Concept : Future
                 Future<Integer> result = channel.read(byteBuffer);

                       Retourne un «Future» avec le nombre d’octet lue (ou écrit)

                 result.get();

                       Attend la fin de l’opération I/O

                 result.get(5, TimeUnit.SECONDS);

                       Attend avec un timout

                 result.isDone();

                       Verifie si l’appel est terminé




vendredi 29 juillet 2011
Asynchronous I/O API
           Concept : CompletionHandler

           channelToClient.read(buffer, counter, new CompletionHandler<Integer,
           AtomicInteger>() {

                 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
Threading model

                 AsynchronousChannelGroup
                       Encapsule le pool de thread, la file d’attente et les
                       autres ressources partagées par les sockets
                       2 implémentations
                           Fixed thread pool
                           Cached thread pool (ou thread pool fournit)



vendredi 29 juillet 2011
Threading model
           Fixed thread pool


                                             CompletionHandler




                           I/O internal
                                          Thread   Thread   Thread




vendredi 29 juillet 2011
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.internalThreadPoolSize




vendredi 29 juillet 2011
Threading model
                 FixedThreadPool              CachedThreadPool ou
                                              ThreadPool fournit
                       Thread partagé entre
                       I/O et callback         Un pool de thread
                                               pour l’I/O et un autre
                       Eviter la contention
                                               pour les callback
                       dans les callback
                                               Attention au context
                                               switch




vendredi 29 juillet 2011
Bench


                       Sur une VM 2vCPU (client et serveur)
                           4000 req/s (50Ko/req et 50Ko/resp)
                           200 Mo/s (Reçu et émis)




vendredi 29 juillet 2011
Multicast non bloquant

       NetworkInterface eth0Itf = NetworkInterface.getByName("eth0");
                  InetAddress mcGroup = InetAddress.getByName("225.0.0.100");

                       DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET)
                               .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                               .bind(new InetSocketAddress(5000))
                               .setOption(StandardSocketOptions.IP_MULTICAST_IF, eth0Itf);

                       MembershipKey key = dc.join(mcGroup, eth0Itf);

                       Selector selector = Selector.open();
                       dc.register(selector, dc.validOps());




vendredi 29 juillet 2011
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
Le reste
                 Mise à jour des API SocketChannel
                       bind(SocketAdress local)
                       setOption(SocketOption name, T Value)
                 Support de SCTP (Protocole de transport réseau)
                 IPV6 sous Windows
                 Support de SDP sous Solaris (protocole RMDA utilisé
                 par Infiniband)


vendredi 29 juillet 2011
File extension
                 Traitement Asynchrone
                 Droits POSIX / ACL NFS / DOS / ...
                 Liens symboliques et vérous
                 Système de fichier et partitions
                 Supervision d’activité sur répertoires et fichiers
                 Parcours de répertoire
                 Méthodes utilitaires


vendredi 29 juillet 2011
java.nio.Path
                 = java.io.File
                 file.toPath() - path.toFile()
                 chemin système du fichier
                            Path p = Paths.get(“/home/user/.myApp“);

                            Iterator<Path> 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
AsynchronousFileChannel
                 Traitement asynchrone non bloquant
                       Chaque read/write donne la position dans le fichier
                       Accède a plusieurs parties du fichier en parallèle
                 Threadsafe
                 Supporte les Locks
                 Options définies sur open(...)



vendredi 29 juillet 2011
AsynchronousFileChannel
              AsynchronousFileChannel afc = AsynchronousFileChannel.open(path,
              StandardOpenOption.CREATE);

              FileLock lock = afc.lock().get();

              afc.write(buffer, 0l).get();
               // Buffer wrote to file

              lock.close();
              afc.close();




vendredi 29 juillet 2011
Files operations
                 Files fournit des utilitaires (guava / commons-io)
                       copy / move / delete /...
                       read* / write / newReader* / newWriter*
                       temp dirs / symlinks / walkFileTree
                 Et les accès systèmes
                       set or get : owner / attribute / posixFilePermissions
                       FileSystem / FileStore


vendredi 29 juillet 2011
FileAttributes
                 Lecture et modification des atributs du fichier
                       BasicFileAttributes, PosixFileAttributes, Dos, ...

                    Path p = Paths.get(“/home/user/.myApp“);

                    BasicFileAttributes attr = Files.readAttributes(file,BasicFileAttributes.class);

                    System.out.println("creationTime: " + attr.creationTime());
                    System.out.println("lastAccessTime: " + attr.lastAccessTime());
                    System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

                    System.out.println("isDirectory: " + attr.isDirectory());
                    System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
                    System.out.println("size: " + attr.size());

                    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------");
                    FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
                    Files.setPosixFilePermissions(file, perms);

vendredi 29 juillet 2011
WatchService

                 Comme un Selector pour les Paths
                       WatchKey k = register(path, event, ...);
                       WatchEvent evt = k.pollEvents();
                       Reset key
                 Boucle infini et Threading à la charge du développeur




vendredi 29 juillet 2011
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<Path> ev = (WatchEvent<Path>)event;
              	        Path filename = ev.context();
              	        //....
                  }
                  boolean valid = key.reset();
                  if (!valid) {
                       break;
                  }
              }




vendredi 29 juillet 2011
DirectoryStream

                 Autorise le forEach() sur les entrées d’un répertoire
                       Glob pattern (“*.java“)
                       RegExp
                       Filtre implémenté
              DirectoryStream<Path> ds = Files.newDirectoryStream(dir, “*.java“);

              for(Path p : ds){
                // ...
              }




vendredi 29 juillet 2011
FileVisitor

                 Files.walkFileTree parcours l’arborescence
                       utilise un FileVisitor
                       Définit des options (FOLLOW_LINKS, ... )
                 FileVisitor est invoqué pour chaque entrée
                       Permet de modifier le parcours
                       Fourni des callbacks pre/post visit File / Directory



vendredi 29 juillet 2011
FileVisitor
                   Path start = ...
                   Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
                       @Override
                       public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
                       {
                         Files.delete(file);
                         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

Contenu connexe

Tendances

java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and filesMarcello Thiry
 
Building layers of defense for your application
Building layers of defense for your applicationBuilding layers of defense for your application
Building layers of defense for your applicationVMware Tanzu
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionBipul Chandra Kar
 
Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19José Paumard
 
SFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driverSFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driverLinaro
 
如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)Cyril Wang
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les basesAntoine Rey
 
Oracle使用者安全設定
Oracle使用者安全設定Oracle使用者安全設定
Oracle使用者安全設定Chien Chung Shen
 
Exception handling
Exception handlingException handling
Exception handlingAnna Pietras
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecturehugo lu
 
Reactive programming
Reactive programmingReactive programming
Reactive programmingSUDIP GHOSH
 
ODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskRuggero Citton
 
Implementing a UEFI BIOS into an Embedded System
Implementing a UEFI BIOS into an Embedded SystemImplementing a UEFI BIOS into an Embedded System
Implementing a UEFI BIOS into an Embedded Systeminsydesoftware
 

Tendances (20)

java.io - streams and files
java.io - streams and filesjava.io - streams and files
java.io - streams and files
 
Java I/O
Java I/OJava I/O
Java I/O
 
Building layers of defense for your application
Building layers of defense for your applicationBuilding layers of defense for your application
Building layers of defense for your application
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19Loom Virtual Threads in the JDK 19
Loom Virtual Threads in the JDK 19
 
SFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driverSFO15-200: Linux kernel generic TEE driver
SFO15-200: Linux kernel generic TEE driver
 
如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)如何使用 Xhprof 分析網站效能 (真實案例2)
如何使用 Xhprof 分析網站效能 (真實案例2)
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Building Netty Servers
Building Netty ServersBuilding Netty Servers
Building Netty Servers
 
Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
 
Oracle使用者安全設定
Oracle使用者安全設定Oracle使用者安全設定
Oracle使用者安全設定
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Exception handling
Exception handlingException handling
Exception handling
 
The linux networking architecture
The linux networking architectureThe linux networking architecture
The linux networking architecture
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Reactive programming
Reactive programmingReactive programming
Reactive programming
 
ODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live DiskODA Backup Restore Utility & ODA Rescue Live Disk
ODA Backup Restore Utility & ODA Rescue Live Disk
 
Implementing a UEFI BIOS into an Embedded System
Implementing a UEFI BIOS into an Embedded SystemImplementing a UEFI BIOS into an Embedded System
Implementing a UEFI BIOS into an Embedded System
 

Similaire à Java Nio 2

Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur SpringAntoine Rey
 
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...Frederic Hardy
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework springAntoine Rey
 
Améliorations dans Java depuis la version 5
Améliorations dans Java depuis la version 5Améliorations dans Java depuis la version 5
Améliorations dans Java depuis la version 5Mamadou Oury Ba
 
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014SOAT
 
Les nouveautés de java 7 et les promesses
Les nouveautés de java 7  et les promessesLes nouveautés de java 7  et les promesses
Les nouveautés de java 7 et les promessesEric Toguem
 
Les nouveautés du Framework .NET 4.5
Les nouveautés du Framework .NET 4.5Les nouveautés du Framework .NET 4.5
Les nouveautés du Framework .NET 4.5Microsoft
 
#5 Java EE5 Client Lourd et Smart Client
#5 Java EE5  Client Lourd  et Smart Client#5 Java EE5  Client Lourd  et Smart Client
#5 Java EE5 Client Lourd et Smart ClientGuillaume Sauthier
 
Présentation de Robotlegs
Présentation de RobotlegsPrésentation de Robotlegs
Présentation de RobotlegsNicolas PENNEC
 
Python et la persistance de données — initiation python 1.5
Python et la persistance de données — initiation python 1.5Python et la persistance de données — initiation python 1.5
Python et la persistance de données — initiation python 1.5Abib Faye
 
Presentation hibernate nfe103
Presentation hibernate nfe103Presentation hibernate nfe103
Presentation hibernate nfe103MRamo2s
 
Arquillian - YaJUG - nov. 2012
Arquillian - YaJUG - nov. 2012Arquillian - YaJUG - nov. 2012
Arquillian - YaJUG - nov. 2012Alexis Hassler
 
Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Jean-Michel Doudoux
 

Similaire à Java Nio 2 (20)

Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
Workshop Spring  3 - Tests et techniques avancées du conteneur SpringWorkshop Spring  3 - Tests et techniques avancées du conteneur Spring
Workshop Spring 3 - Tests et techniques avancées du conteneur Spring
 
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
Atoum, le framework de tests unitaires pour PHP 5.3 simple, moderne et intuit...
 
Les dessous du framework spring
Les dessous du framework springLes dessous du framework spring
Les dessous du framework spring
 
Améliorations dans Java depuis la version 5
Améliorations dans Java depuis la version 5Améliorations dans Java depuis la version 5
Améliorations dans Java depuis la version 5
 
Multi threadingJava
Multi threadingJavaMulti threadingJava
Multi threadingJava
 
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014Nio sur Netty par Mouhcine Moulou - 3 avril 2014
Nio sur Netty par Mouhcine Moulou - 3 avril 2014
 
Les nouveautés de java 7 et les promesses
Les nouveautés de java 7  et les promessesLes nouveautés de java 7  et les promesses
Les nouveautés de java 7 et les promesses
 
Les nouveautés du Framework .NET 4.5
Les nouveautés du Framework .NET 4.5Les nouveautés du Framework .NET 4.5
Les nouveautés du Framework .NET 4.5
 
#5 Java EE5 Client Lourd et Smart Client
#5 Java EE5  Client Lourd  et Smart Client#5 Java EE5  Client Lourd  et Smart Client
#5 Java EE5 Client Lourd et Smart Client
 
Présentation de Robotlegs
Présentation de RobotlegsPrésentation de Robotlegs
Présentation de Robotlegs
 
Python et la persistance de données — initiation python 1.5
Python et la persistance de données — initiation python 1.5Python et la persistance de données — initiation python 1.5
Python et la persistance de données — initiation python 1.5
 
Nouveautés Java 9-10-11
Nouveautés Java 9-10-11Nouveautés Java 9-10-11
Nouveautés Java 9-10-11
 
Kotlin coroutines
Kotlin coroutinesKotlin coroutines
Kotlin coroutines
 
Presentation hibernate nfe103
Presentation hibernate nfe103Presentation hibernate nfe103
Presentation hibernate nfe103
 
Arquillian - YaJUG - nov. 2012
Arquillian - YaJUG - nov. 2012Arquillian - YaJUG - nov. 2012
Arquillian - YaJUG - nov. 2012
 
Nouveautés de java 8
Nouveautés de java 8Nouveautés de java 8
Nouveautés de java 8
 
Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017Java 9 modulo les modules devoxx fr 2017
Java 9 modulo les modules devoxx fr 2017
 
fortran 2.pdf
fortran 2.pdffortran 2.pdf
fortran 2.pdf
 
cours6.pdf
cours6.pdfcours6.pdf
cours6.pdf
 
Introduction a Java
Introduction a JavaIntroduction a Java
Introduction a Java
 

Plus de Publicis Sapient Engineering

XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humainXebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humainPublicis Sapient Engineering
 
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveurXebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveurPublicis Sapient Engineering
 
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...Publicis Sapient Engineering
 
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin Publicis Sapient Engineering
 
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?Publicis Sapient Engineering
 
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?Publicis Sapient Engineering
 
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribuéXebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribuéPublicis Sapient Engineering
 
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...Publicis Sapient Engineering
 
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !Publicis Sapient Engineering
 
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des datavizXebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des datavizPublicis Sapient Engineering
 
XebiCon'18 - Architecturer son application mobile pour la durabilité
XebiCon'18 - Architecturer son application mobile pour la durabilitéXebiCon'18 - Architecturer son application mobile pour la durabilité
XebiCon'18 - Architecturer son application mobile pour la durabilitéPublicis Sapient Engineering
 
XebiCon'18 - Sécuriser son API avec OpenID Connect
XebiCon'18 - Sécuriser son API avec OpenID ConnectXebiCon'18 - Sécuriser son API avec OpenID Connect
XebiCon'18 - Sécuriser son API avec OpenID ConnectPublicis Sapient Engineering
 
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...Publicis Sapient Engineering
 
XebiCon'18 - La sécurité, douce illusion même en 2018
XebiCon'18 - La sécurité, douce illusion même en 2018XebiCon'18 - La sécurité, douce illusion même en 2018
XebiCon'18 - La sécurité, douce illusion même en 2018Publicis Sapient Engineering
 
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...Publicis Sapient Engineering
 
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...Publicis Sapient Engineering
 

Plus de Publicis Sapient Engineering (20)

XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humainXebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
XebiCon'18 - L'algorithme de reconnaissance de formes par le cerveau humain
 
Xebicon'18 - IoT: From Edge to Cloud
Xebicon'18 - IoT: From Edge to CloudXebicon'18 - IoT: From Edge to Cloud
Xebicon'18 - IoT: From Edge to Cloud
 
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveurXebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
Xebicon'18 - Spark in jail : conteneurisez vos traitements data sans serveur
 
XebiCon'18 - Modern Infrastructure
XebiCon'18 - Modern InfrastructureXebiCon'18 - Modern Infrastructure
XebiCon'18 - Modern Infrastructure
 
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
XebiCon'18 - La Web App d'aujourd'hui et de demain : état de l'art et bleedin...
 
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
XebiCon'18 - Des notebook pour le monitoring avec Zeppelin
 
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
XebiCon'18 - Event Sourcing et RGPD, incompatibles ?
 
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
XebiCon'18 - Deno, le nouveau NodeJS qui inverse la tendance ?
 
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribuéXebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
XebiCon'18 - Boostez vos modèles avec du Deep Learning distribué
 
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
XebiCon'18 - Comment j'ai développé un jeu vidéo avec des outils de développe...
 
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
XebiCon'18 - Les utilisateurs finaux, les oubliés de nos produits !
 
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des datavizXebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
XebiCon'18 - Comment fausser l'interprétation de vos résultats avec des dataviz
 
XebiCon'18 - Le développeur dans la Pop Culture
XebiCon'18 - Le développeur dans la Pop Culture XebiCon'18 - Le développeur dans la Pop Culture
XebiCon'18 - Le développeur dans la Pop Culture
 
XebiCon'18 - Architecturer son application mobile pour la durabilité
XebiCon'18 - Architecturer son application mobile pour la durabilitéXebiCon'18 - Architecturer son application mobile pour la durabilité
XebiCon'18 - Architecturer son application mobile pour la durabilité
 
XebiCon'18 - Sécuriser son API avec OpenID Connect
XebiCon'18 - Sécuriser son API avec OpenID ConnectXebiCon'18 - Sécuriser son API avec OpenID Connect
XebiCon'18 - Sécuriser son API avec OpenID Connect
 
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
XebiCon'18 - Structuration du Temps et Dynamique de Groupes, Théorie organisa...
 
XebiCon'18 - Spark NLP, un an après
XebiCon'18 - Spark NLP, un an aprèsXebiCon'18 - Spark NLP, un an après
XebiCon'18 - Spark NLP, un an après
 
XebiCon'18 - La sécurité, douce illusion même en 2018
XebiCon'18 - La sécurité, douce illusion même en 2018XebiCon'18 - La sécurité, douce illusion même en 2018
XebiCon'18 - La sécurité, douce illusion même en 2018
 
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
XebiCon'18 - Utiliser Hyperledger Fabric pour la création d'une blockchain pr...
 
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
XebiCon'18 - Ce que l'histoire du métro Parisien m'a enseigné sur la création...
 

Java Nio 2

  • 1. Java 7 Asynchronous I/O (NIO2) Julien Buret Séven Le Mesle vendredi 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 Notification vendredi 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.7 vendredi 29 juillet 2011
  • 4. Asynchronous I/O API Créer un channel AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withFixedThreadPool(4, threadFactory); AsynchronousServerSocketChannel socketChannel = AsynchronousServerSocketChannel.open (channelGroup); socketChannel.bind(new InetSocketAddress(8080)); Future<AsynchronousSocketChannel> resAccept = socketChannel.accept(); Future<Integer> res = resAccept.get().read(ByteBuffer.allocate(512)); vendredi 29 juillet 2011
  • 5. Asynchronous I/O API Concept : Future Future<Integer> result = channel.read(byteBuffer); Retourne un «Future» avec le nombre d’octet lue (ou écrit) result.get(); Attend la fin de l’opération I/O result.get(5, TimeUnit.SECONDS); Attend avec un timout result.isDone(); Verifie si l’appel est terminé vendredi 29 juillet 2011
  • 6. Asynchronous I/O API Concept : CompletionHandler channelToClient.read(buffer, counter, new CompletionHandler<Integer, AtomicInteger>() { 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 file d’attente et les autres ressources partagées par les sockets 2 implémentations 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 Thread vendredi 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.internalThreadPoolSize vendredi 29 juillet 2011
  • 10. Threading model FixedThreadPool CachedThreadPool ou ThreadPool fournit Thread partagé entre I/O et callback Un pool de thread pour l’I/O et un autre Eviter la contention pour les callback dans les callback Attention au context switch vendredi 29 juillet 2011
  • 11. Bench Sur une VM 2vCPU (client et serveur) 4000 req/s (50Ko/req et 50Ko/resp) 200 Mo/s (Reçu et émis) vendredi 29 juillet 2011
  • 12. Multicast non bloquant NetworkInterface eth0Itf = NetworkInterface.getByName("eth0"); InetAddress mcGroup = InetAddress.getByName("225.0.0.100"); DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET) .setOption(StandardSocketOptions.SO_REUSEADDR, true) .bind(new InetSocketAddress(5000)) .setOption(StandardSocketOptions.IP_MULTICAST_IF, eth0Itf); MembershipKey key = dc.join(mcGroup, eth0Itf); Selector selector = Selector.open(); dc.register(selector, dc.validOps()); 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 réseau) IPV6 sous Windows Support de SDP sous Solaris (protocole RMDA utilisé par Infiniband) vendredi 29 juillet 2011
  • 15. File extension Traitement Asynchrone Droits POSIX / ACL NFS / DOS / ... Liens symboliques et vérous Système de fichier et partitions Supervision d’activité sur répertoires et fichiers Parcours de répertoire Méthodes utilitaires vendredi 29 juillet 2011
  • 16. java.nio.Path = java.io.File file.toPath() - path.toFile() chemin système du fichier Path p = Paths.get(“/home/user/.myApp“); Iterator<Path> 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 fichier Accède a plusieurs parties du fichier en parallèle Threadsafe Supporte les Locks Options définies 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 file 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 accès systèmes set or get : owner / attribute / posixFilePermissions FileSystem / FileStore vendredi 29 juillet 2011
  • 20. FileAttributes Lecture et modification des atributs du fichier BasicFileAttributes, PosixFileAttributes, Dos, ... Path p = Paths.get(“/home/user/.myApp“); BasicFileAttributes attr = Files.readAttributes(file,BasicFileAttributes.class); System.out.println("creationTime: " + attr.creationTime()); System.out.println("lastAccessTime: " + attr.lastAccessTime()); System.out.println("lastModifiedTime: " + attr.lastModifiedTime()); System.out.println("isDirectory: " + attr.isDirectory()); System.out.println("isSymbolicLink: " + attr.isSymbolicLink()); System.out.println("size: " + attr.size()); Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); Files.setPosixFilePermissions(file, 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 infini et Threading à la charge du développeur vendredi 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<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); //.... } boolean valid = key.reset(); if (!valid) { break; } } vendredi 29 juillet 2011
  • 23. DirectoryStream Autorise le forEach() sur les entrées d’un répertoire Glob pattern (“*.java“) RegExp Filtre implémenté DirectoryStream<Path> ds = Files.newDirectoryStream(dir, “*.java“); for(Path p : ds){ // ... } vendredi 29 juillet 2011
  • 24. FileVisitor Files.walkFileTree parcours l’arborescence utilise un FileVisitor Définit des options (FOLLOW_LINKS, ... ) FileVisitor est invoqué pour chaque entrée Permet de modifier le parcours Fourni des callbacks pre/post visit File / Directory vendredi 29 juillet 2011
  • 25. FileVisitor Path start = ... Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); 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