SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
<Insert Picture Here>




Java SE 7: New and Improved APIs
Agenda

 •    New IO updates (NIO2 – JSR 203)
 •    Concurrency updates (JSR-166y)
 •    Collections updates
 •    Client
      •  Shaped/translucent windows
      •  JLayer component
 •  JDBC 4.1
 •  Java APIs for XML




                                        3
                                        3
New I/O 2 (NIO2) Libraries
JSR 203


    •  Original Java I/O APIs presented challenges for
       developers
      •    Not designed to be extensible
      •    Many methods do not throw exceptions as expected
      •    rename() method works inconsistently
      •    Developers want greater access to file metadata
    •  Java NIO2 solves these problems




                                                              4
                                                              4
Java NIO2 Features

  •  Path is a replacement for File
    •  Biggest impact on developers
  •  Better directory support
    •  list() method can stream via iterator
    •  Entries can be filtered using regular expressions in API
  •  Symbolic link support
  •  java.nio.file.Filesystem
    •  interface to a filesystem (FAT, ZFS, Zip archive, network, etc)
  •  java.nio.file.attribute package
    •  Access to file metadata




                                                                   5
                                                                   5
Path Class
    •  Equivalent of java.io.File in the new API
        –  Immutable
    •  Methods to access and manipulate Path
    •  Numerous ways to create a Path
       –  From Paths and FileSystem

     //Make a reference to the path
     Path home = Paths.get(“/home/fred”);
     //Resolve tmp from /home/fred -> /home/fred/tmp
     Path tmpPath = home.resolve(“tmp”);
     //Create a relative path from tmp -> ..
     Path relativePath = tmpPath.relativize(home)
     File file = relativePath.toFile();


                                                   6
                                                   6
File Operation – Create, Read, Write
    •  Easy to open file for reading or writing
     Path file = Paths.get(“/home/fred/readme.txt”);
     InputStream is = Files.newInputStream(file);
     OutputStream os = Files.newOutputStream(file);
    •  More advanced options for opening or creating files
       –  Append to existing file, sparse file, delete on closing the file,
          etc.
    Path file = Paths.get(“/home/fred/readme.txt”);
    //Append to file
    Writer writer = Files.newBufferedWriter(file
        , StandardCharset.UTF_8
        , StandardOpenOption.WRITE
        , StandardOpenOption.APPEND);

                                                                       7
                                                                        7
File Operation – Copy, Move

   •  File copy is really easy
       –  With fine grain control
      Path src = Paths.get(“/home/fred/readme.txt”);
      Path dst = Paths.get(“/home/fred/copy_readme.txt”);
     Files.copy(src, dst,
          StandardCopyOption.COPY_ATTRIBUTES,
          StandardCopyOption.REPLACE_EXISTING);
   •  File move is supported
       –  Optional atomic move supported
      Path src = Paths.get(“/home/fred/readme.txt”);
      Path dst = Paths.get(“/home/fred/readme.1st”);
      Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);


                                                  8
                                                  8
File Operation – Links
•  Hard and symbolic/soft links optionally supported
•  API based on long standing Unix semantics
    •  Windows Vista or newer with NTFS
•  File operations on symbolic links are followed by
 default except
  •  delete, move, walkFileTree
•  Creating hard link
  Path src = Paths.get(“/home/fred/readme.txt”);
  Path linkFile = Paths.get(“/home/fred/readme.lnk”);
  Files.createLink(linkFile, src);
•  Creating symbolic/soft link

   Files.createSymbolicLink(linkFile, src);


                                                       9
                                                       9
Directories
•  DirectoryStream iterate over entries
   –  Scales to large directories
   –  Uses less resources
   –  Smooth out response time for remote file systems
   –  Implements Iterable and Closeable for productivity
•  Filtering support
    –  Build-in support for glob, regex and custom filters

  Path srcPath = Paths.get(“/home/fred/src”);
  try (DirectoryStream<Path> dir =
       srcPath.newDirectoryStream(“*.java”)) {
    for (Path file: dir)
       System.out.println(file.getName());
  }


                                                             10
                                                             10
Recursive Operation
•  Interator to walk a file tree from a given starting point
•  FileVisitor invoked for each file/directory
 encountered
  –  Based on visitor pattern
•  Depth first, invoked twice for each directory (pre/post)
•  Easy to develop recursive operations

public interface FileVisitor<T> {
  FileVisitResult preVisitDirectory(T dir,
    BasicFileAttributes attrs);
  FileVisitResult visitFile(T file, BasicFileAttributes attrs);
  FileVisitResult visitFileFailed(T file, IOException ex);
  FileVisitResult postVisitDirectory(T dir, IOException ex);
}




                                                               11
                                                               11
FileVisitor Example

 public class DeleteTildaFile
     extends SimpleFileVisitor<Path> {
     @Override
     public FileVisitResult visitFile(Path file,
         BasicFileAttributes attrs) {
       if (file.toFile().getName().endsWith(“~”))
         Files.delete(file);
       return (FileVisitResult.CONTINUE);
     }
 }

  Path src = Paths.get(“/home/fred/src”);
  Files.walkFileTree(src, new DeleteTildaFile());



                                                    12
                                                    12
File Attributes
•  Meta-data associated with file
   –  File owner, permissions, timestamps, DOS attributes,
      extended attributes
   –  Diverse and highly platform/file system specific
•  Approach: group related attributes
    –  Providing typesafe and bulk access

public interface PosixFileAttribute extends BasicFileAttribute {
     UserPrincipal owner();
     GroupPrincipal group();
     Set<PosixFilePermission> permissions();
}
•  Views to access these attributes
    –  POSIX, ACL, DOS, extended, user defined, etc



                                                             13
                                                             13
File Attributes – Read, Set, Query
  •  Reading file attributes

  PosixFileAttributeView view = Files.getFileAttributeView(
       file, PosixFileAttributeView.class);
  PosixFileAttributes attr = view.readAttributes();
  System.out.println(“file owner = “ + attr.owner());

  •  Setting file attributes
  Set<PosixFilePermission> perms = PosixFilePermissions
       .fromString(“rw-r-----”);
  Files.setPosixFilePermissions(file, perms);

  •  Querying supported attribute views
  Set<String> views = FileSystems.getDefault()
       .supportedFileAttributeViews();




                                                      14
                                                      14
File Change Notifications
 •  Watch files and directories for changes
    –  Typically polled
 •  WatchService
     –  Watches registered objects for changes and events
     –  Makes use of native event notification facility where possible
     –  Monitors directories, generates events when files are created,
        deleted or modified
     –  Extendable to other objects and events
     –  Deliberately a low level interface




                                                                    15
                                                                    15
Major Classes
•  WatchService
    –  Watches registered objects for changes and events
    –  Allows multiple threads to poll/take events
•  Watchable
    –  An object that is registered with WatchService
    –  Implemented by Path
•  WatchKey
    –  An object representing a registration
•  WatchEvent
    –  An event




                                                           16
                                                           16
WatchService Example
  •  Registering a WatchService
    WatchService watcher =
      FileSystems.getDefault().newWatchService();
    Path tmp = Paths.get(“/home/fred/tmp”);
    tmp.register(watcher, StandardWatchEventKinds.ENTRY_CREATE
         , StandardWatchEventKinds.ENTRY_DELETE);
  •  Retrieving and processing events
    while (true) {
         WatchKey key = watcher.take(); //non-blocking – poll()
      for (WatchEvent<?> event: key.pollEvents()) {
           if (StandardWatchEventKinds.ENTRY_CREATE == event.kind() {
             Path newFile = (Path)event.context();
            ...
           }
         }
         key.reset();
    }
                                                     17
                                                     17
FileSystem and FileStore
•  FileSystem is an interface to a file system
    –  Also factory for files and other objects
•  Retrieving the default filesystem
 FileSystem fs = FileSystems.getDefault();
•  Creating new file systems – eg. ZIP/JAR file system
 Map<String, String> attrs = new HashMap<>();
 attrs.put(“create”, “true”);
 FileSystem zipfs = FileSystems.newFileSystems(
      “jar:file:/opt/tmp/myzip.zip”, attrs);
•  FileStore represents storage devices
    –  Storage pools, partitions, volumes, etc
•  Provider interface to implement new file system type



                                                          18
                                                          18
Asynchronous I/O
•  java.io a short history
    –  Pre JDK 1.4 – blocking I/O
    –  JDK 1.4 onwards – non blocking I/O, memory mapped files, file
       lock, channels and buffers
    –  JDK 7 – asynchronous I/O
•  Provides asynchronous I/O to both sockets and files
    –  Take advantage of operating systems I/O facilities where available
•  Programming styles
    –  Polling – I/O returns a Future object
        •  Poll to test for I/O completion
    –  Callback – specify a CompletionHandler when performing I/O
        •  CompletionHandler invoked when I/O completes or fails




                                                                       19
                                                                       19
Asynchronous I/O – Example


  AsynchronousSocketChannel chan =
      AsynchronousSocketChannel.open();

  //Non blocking connect/SOCK_NONBLOCK – polling
  Future<Void> result = chan.connect(new InetSocketAddress(...));

  //Perform some operation until done result.isDone()
  result.get();

  ByteBuffer buff = ByteBuffer.allocate(EIGHT_K);

  //Perform the read – callback
  chan.read(buff, buff, new MyCompletionHandler());



                                                20
                                                20
Asynchronous I/O – Example

    pubilc class MyCompletionHandler
        implements CompletionHandler<Integer, ByteBuffer> {

          //Invoked when operation is completed
        public void completed(Integer result, ByteBuffer buff) {
            ...
          }

            //Invoked when operation fails
            public void failed(Throwable ex, ByteBuffer buff) {
              ...
        }
    }




                                                   21
                                                   21
Concurrency APIs

  •  JSR166y
    •  Update to JSR166x which was an update to JSR166
  •  Adds a lightweight task framework
    •  Also referred to as Fork/Join
  •  Phaser
    •  Barrier similar to CyclicBarrier and CountDownLatch




                                                         22
                                                             22
Fork Join Framework
•  Goal is to take advantage of multiple processor
•  Designed for task that can be broken down into
 smaller pieces
  –  Eg. Fibonacci number fib(10) = fib(9) + fib(8)
•  Typical algorithm that uses fork join


   if I can manage the task
       perform the task
   else
       fork task into x number of smaller/similar
   task

     join the results

                                                      23
                                                      23
Key Classes
   •  ForkJoinPool
       –  Executor service for running ForkJoinTask
   •  ForkJoinTask
       –  The base class for forkjoin task
   •  RecursiveAction
       –  A subclass of ForkJoinTask
       –  A recursive resultless task
       –  Implements compute() abstract method to perform
          calculation
   •  RecursiveTask
       –  Similar to RecursiveAction but returns a result




                                                            24
                                                            24
ForkJoin Example – Fibonacci
public class Fibonacci extends RecursiveTask<Integer> {
    private final int number;
    public Fibonacci(int n) { number = n; }

     @Override protected Integer compute() {
         switch (number) {
             case 0: return (0);
             case 1: return (1);
             default:
                 Fibonacci f1 = new Fibonacci(number – 1);
                 Fibonacci f2 = new Fibonacci(number – 2);
                 f1.fork(); f2.fork();
                 return (f1.join() + f2.join());
         }
     }
}




                                                             25
                                                             25
ForkJoin Example – Fibonacci

ForkJoinPool pool = new ForkJoinPool();
Fibonacci r = new Fibonacci(10);
pool.submit(r);

while (!r.isDone()) {
    //Do some work
    ...
}

System.out.println("Result of fib(10) = “ + r.get());




                                          26
                                          26
Collections Updates

  •  TransferQueue interface
    •  Extension to BlockingQueue
    •  Implemented by LinkedTransferQueue


  •  Producers may, or may not, wait for consumer to
    receive element
  •  Can be capacity bounded or unbounded




                                                       27
                                                       27
Client Libraries

  •  Nimbus Look and Feel
  •  Platform APIs for shaped and translucent windows
  •  JLayer (formerly from Swing labs)
  •  Optimised 2D rendering




                                                        28
                                                        28
Shaped and Translucent Windows

•  Uniform translucency




•  Gradient translucency




•  Shaped


                                  29
                                  29
Shaped Window Example
public class ShapedWindow extends JFrame {
  public ShapedWindow() {
    super("ShapedWindow");
    addComponentListener(new ComponentAdapter() {
      @Override
      public void componentResized(ComponentEvent e) {
        setShape(
            new Ellipse2D.Double(0,0, getWidth(),getHeight()));
      }
    });
    setUndecorated(true);
  }
}




                                                      30
                                                       30
Nimbus Look and Feel
•  Better than Metal for cross platform look-and-feel
•  Introduced in Java SE 6u10, now part of Swing
•  Not the default L&F




                                                        31
                                                        31
JLayer and LayerUI

 •  A decorator for Swing components
     –  Layer on top of JPanel instead of using
        GlassPane
     –  Paint on Swing components without
        subclassing the component
     –  Can intercept AWT events
 •  LayerUI performs the painting and event
  processing




                                                  32
                                                  32
LayerUI in Detail

 •  Extend and typically override the following
     •  paint(Graphics, JComponent) – draw on the component
     •  installUI(JComponent) – configure the component eg. setting
        the event mask
     •  processXXXEvent – process events (mouse, keyboard, etc)




                                                            33
                                                            33
JLayer Example

  public class MyDecorator extends LayerUI<JPanel> {
    @Override
    public void installUI(JComponent c) {
      super.installUI(c);
      JLayer l = (JLayer)c;
      l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK);
    }

      @Override
      public void paint(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        //Draw on g2d
        ...
      }
  }

                                                34
                                                34
JLayer Example


  //Create panel
  JPanel myPanel =
  ...

  MyDecorator myDecorator = new MyDecorator();

  JLayer<JPanel> jLayer =
    new Jlayer<JPanel>(myPanel, myDecorator);




                                           35
                                            35
JDBC 4.1 Changes

•  Allow Connection, ResultSet and Statement
   objects to be used with the try-with-resources
   statement
   •  Implement AutoCloseable interface
•  RowSetFactory and RowSetProvider classes
   added to javax.sql.rowset package




                                                    36
                                                    36
Java APIs for XML

•  JAXP 1.4.5 (Parsing)
   •  Bug fixes, conformance, security, performance
   •  StAX upgraded to version 1.2
•  JAXB 2.2.3 (Binding)
   •  Minor changes to XMLElement interface
•  JAX-WS 2.2.4 (Web Services)
   •  Minor changes
   •  Support for Async Servlet Transport using Servlet 3.0 API




                                                                  37
                                                                  37
java.util.Objects

  •  Utility methods for operating on objects
     –  Methods are null safe and null tolerant
  •  Objects.deepEquals(Object a, Object b)
      –  Deep equals
  •  Objects.hashCode(Object o)
      –  Return hash code of non-null argument or 0 for null
         argument
  •  Objects.requireNonNull(T o)
      –  Throws NullPointerException if o is null




                                                               38
                                                               38
Conclusions

  •  Java SE 7 provides useful new APIs
  •  File handling APIs make routine tasks much simpler
  •  Fork-join framework simplifies concurrent decomposition of
     large tasks
  •  Many other useful features
  •  Java continues to deliver features developers require




                                                       39
                                                       39
40
40

Weitere ähnliche Inhalte

Was ist angesagt?

Content server installation guide
Content server installation guideContent server installation guide
Content server installation guideNaveed Bashir
 
Fuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FSFuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FSChetan Giridhar
 
DSpace 4.2 Basics & Configuration
DSpace 4.2 Basics & ConfigurationDSpace 4.2 Basics & Configuration
DSpace 4.2 Basics & ConfigurationDuraSpace
 
XOOPS 2.6.0 Service Manager
XOOPS 2.6.0  Service Manager XOOPS 2.6.0  Service Manager
XOOPS 2.6.0 Service Manager xoopsproject
 
Introduction to YUI PHP Loader
Introduction to YUI PHP LoaderIntroduction to YUI PHP Loader
Introduction to YUI PHP LoaderChad Auld
 
eZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedeZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedBertrand Dunogier
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPSxoopsproject
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaVasil Remeniuk
 
DSpace Manual for BALID Trainee
DSpace Manual for BALID Trainee DSpace Manual for BALID Trainee
DSpace Manual for BALID Trainee Nur Ahammad
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collectorInfiniFlux
 
2-5-14 “DSpace User Interface Innovation” Presentation Slides
2-5-14 “DSpace User Interface Innovation” Presentation Slides2-5-14 “DSpace User Interface Innovation” Presentation Slides
2-5-14 “DSpace User Interface Innovation” Presentation SlidesDuraSpace
 
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015die.agilen GmbH
 

Was ist angesagt? (19)

Persistences
PersistencesPersistences
Persistences
 
Content server installation guide
Content server installation guideContent server installation guide
Content server installation guide
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
8.C#
8.C#8.C#
8.C#
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Fuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FSFuse'ing python for rapid development of storage efficient FS
Fuse'ing python for rapid development of storage efficient FS
 
DSpace 4.2 Basics & Configuration
DSpace 4.2 Basics & ConfigurationDSpace 4.2 Basics & Configuration
DSpace 4.2 Basics & Configuration
 
XOOPS 2.6.0 Service Manager
XOOPS 2.6.0  Service Manager XOOPS 2.6.0  Service Manager
XOOPS 2.6.0 Service Manager
 
Introduction to YUI PHP Loader
Introduction to YUI PHP LoaderIntroduction to YUI PHP Loader
Introduction to YUI PHP Loader
 
Hibernate java and_oracle
Hibernate java and_oracleHibernate java and_oracle
Hibernate java and_oracle
 
Dspace software
Dspace softwareDspace software
Dspace software
 
JSON in Solr: from top to bottom
JSON in Solr: from top to bottomJSON in Solr: from top to bottom
JSON in Solr: from top to bottom
 
eZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisitedeZ Publish cluster unleashed revisited
eZ Publish cluster unleashed revisited
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
 
SBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius ValatkaSBT by Aform Research, Saulius Valatka
SBT by Aform Research, Saulius Valatka
 
DSpace Manual for BALID Trainee
DSpace Manual for BALID Trainee DSpace Manual for BALID Trainee
DSpace Manual for BALID Trainee
 
InfiniFlux collector
InfiniFlux collectorInfiniFlux collector
InfiniFlux collector
 
2-5-14 “DSpace User Interface Innovation” Presentation Slides
2-5-14 “DSpace User Interface Innovation” Presentation Slides2-5-14 “DSpace User Interface Innovation” Presentation Slides
2-5-14 “DSpace User Interface Innovation” Presentation Slides
 
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
 

Ähnlich wie Javase7 1641812

Exploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSExploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSCsaba Fitzl
 
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsSam Bowne
 
Fuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientFuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientVishal Kanaujia
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the futureMasoud Kalali
 
Hadoop 20111117
Hadoop 20111117Hadoop 20111117
Hadoop 20111117exsuns
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.pptHelalMirzad
 
File system1.pptx
File system1.pptxFile system1.pptx
File system1.pptxSamar954063
 
File management53(1)
File management53(1)File management53(1)
File management53(1)myrajendra
 
LinuxForensicsForNon-LinuxFolks.pdf
LinuxForensicsForNon-LinuxFolks.pdfLinuxForensicsForNon-LinuxFolks.pdf
LinuxForensicsForNon-LinuxFolks.pdfssusere6dc9d
 
SQL Server 2012 - FileTables
SQL Server 2012 - FileTables SQL Server 2012 - FileTables
SQL Server 2012 - FileTables Sperasoft
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsSam Bowne
 
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsSam Bowne
 
File Management & Access Control
File Management & Access Control File Management & Access Control
File Management & Access Control YuvrajWadavale
 

Ähnlich wie Javase7 1641812 (20)

Os6
Os6Os6
Os6
 
AHUG Presentation: Fun with Hadoop File Systems
AHUG Presentation: Fun with Hadoop File SystemsAHUG Presentation: Fun with Hadoop File Systems
AHUG Presentation: Fun with Hadoop File Systems
 
Exploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOSExploiting Directory Permissions on macOS
Exploiting Directory Permissions on macOS
 
Ch10 file system interface
Ch10   file system interfaceCh10   file system interface
Ch10 file system interface
 
File system
File systemFile system
File system
 
CNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X SystemsCNIT 152: 13 Investigating Mac OS X Systems
CNIT 152: 13 Investigating Mac OS X Systems
 
Fuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficientFuse'ing python for rapid development of storage efficient
Fuse'ing python for rapid development of storage efficient
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the future
 
Hadoop 20111117
Hadoop 20111117Hadoop 20111117
Hadoop 20111117
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
 
File system1.pptx
File system1.pptxFile system1.pptx
File system1.pptx
 
PyFilesystem
PyFilesystemPyFilesystem
PyFilesystem
 
File management53(1)
File management53(1)File management53(1)
File management53(1)
 
Systems Programming - File IO
Systems Programming - File IOSystems Programming - File IO
Systems Programming - File IO
 
CH11.pdf
CH11.pdfCH11.pdf
CH11.pdf
 
LinuxForensicsForNon-LinuxFolks.pdf
LinuxForensicsForNon-LinuxFolks.pdfLinuxForensicsForNon-LinuxFolks.pdf
LinuxForensicsForNon-LinuxFolks.pdf
 
SQL Server 2012 - FileTables
SQL Server 2012 - FileTables SQL Server 2012 - FileTables
SQL Server 2012 - FileTables
 
CNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X SystemsCNIT 152 13 Investigating Mac OS X Systems
CNIT 152 13 Investigating Mac OS X Systems
 
CNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X SystemsCNIT 121: 13 Investigating Mac OS X Systems
CNIT 121: 13 Investigating Mac OS X Systems
 
File Management & Access Control
File Management & Access Control File Management & Access Control
File Management & Access Control
 

Mehr von Vinay H G

Continuous integration using jenkins
Continuous integration using jenkinsContinuous integration using jenkins
Continuous integration using jenkinsVinay H G
 
Developers best practices_tutorial
Developers best practices_tutorialDevelopers best practices_tutorial
Developers best practices_tutorialVinay H G
 
Javamagazine20140304 dl
Javamagazine20140304 dlJavamagazine20140304 dl
Javamagazine20140304 dlVinay H G
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorialVinay H G
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updatesVinay H G
 
Why should i switch to Java SE 7
Why should i switch to Java SE 7Why should i switch to Java SE 7
Why should i switch to Java SE 7Vinay H G
 
Lambda Expressions
Lambda ExpressionsLambda Expressions
Lambda ExpressionsVinay H G
 
Tutorial storybook
Tutorial storybookTutorial storybook
Tutorial storybookVinay H G
 
Virtual dev-day-java7-keynote-1641807
Virtual dev-day-java7-keynote-1641807Virtual dev-day-java7-keynote-1641807
Virtual dev-day-java7-keynote-1641807Vinay H G
 
Agile practice-2012
Agile practice-2012Agile practice-2012
Agile practice-2012Vinay H G
 
OAuth with Restful Web Services
OAuth with Restful Web Services OAuth with Restful Web Services
OAuth with Restful Web Services Vinay H G
 
Java Garbage Collection
Java Garbage CollectionJava Garbage Collection
Java Garbage CollectionVinay H G
 

Mehr von Vinay H G (12)

Continuous integration using jenkins
Continuous integration using jenkinsContinuous integration using jenkins
Continuous integration using jenkins
 
Developers best practices_tutorial
Developers best practices_tutorialDevelopers best practices_tutorial
Developers best practices_tutorial
 
Javamagazine20140304 dl
Javamagazine20140304 dlJavamagazine20140304 dl
Javamagazine20140304 dl
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Java 8 selected updates
Java 8 selected updatesJava 8 selected updates
Java 8 selected updates
 
Why should i switch to Java SE 7
Why should i switch to Java SE 7Why should i switch to Java SE 7
Why should i switch to Java SE 7
 
Lambda Expressions
Lambda ExpressionsLambda Expressions
Lambda Expressions
 
Tutorial storybook
Tutorial storybookTutorial storybook
Tutorial storybook
 
Virtual dev-day-java7-keynote-1641807
Virtual dev-day-java7-keynote-1641807Virtual dev-day-java7-keynote-1641807
Virtual dev-day-java7-keynote-1641807
 
Agile practice-2012
Agile practice-2012Agile practice-2012
Agile practice-2012
 
OAuth with Restful Web Services
OAuth with Restful Web Services OAuth with Restful Web Services
OAuth with Restful Web Services
 
Java Garbage Collection
Java Garbage CollectionJava Garbage Collection
Java Garbage Collection
 

Kürzlich hochgeladen

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 

Kürzlich hochgeladen (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Javase7 1641812

  • 1.
  • 2. <Insert Picture Here> Java SE 7: New and Improved APIs
  • 3. Agenda •  New IO updates (NIO2 – JSR 203) •  Concurrency updates (JSR-166y) •  Collections updates •  Client •  Shaped/translucent windows •  JLayer component •  JDBC 4.1 •  Java APIs for XML 3 3
  • 4. New I/O 2 (NIO2) Libraries JSR 203 •  Original Java I/O APIs presented challenges for developers •  Not designed to be extensible •  Many methods do not throw exceptions as expected •  rename() method works inconsistently •  Developers want greater access to file metadata •  Java NIO2 solves these problems 4 4
  • 5. Java NIO2 Features •  Path is a replacement for File •  Biggest impact on developers •  Better directory support •  list() method can stream via iterator •  Entries can be filtered using regular expressions in API •  Symbolic link support •  java.nio.file.Filesystem •  interface to a filesystem (FAT, ZFS, Zip archive, network, etc) •  java.nio.file.attribute package •  Access to file metadata 5 5
  • 6. Path Class •  Equivalent of java.io.File in the new API –  Immutable •  Methods to access and manipulate Path •  Numerous ways to create a Path –  From Paths and FileSystem //Make a reference to the path Path home = Paths.get(“/home/fred”); //Resolve tmp from /home/fred -> /home/fred/tmp Path tmpPath = home.resolve(“tmp”); //Create a relative path from tmp -> .. Path relativePath = tmpPath.relativize(home) File file = relativePath.toFile(); 6 6
  • 7. File Operation – Create, Read, Write •  Easy to open file for reading or writing Path file = Paths.get(“/home/fred/readme.txt”); InputStream is = Files.newInputStream(file); OutputStream os = Files.newOutputStream(file); •  More advanced options for opening or creating files –  Append to existing file, sparse file, delete on closing the file, etc. Path file = Paths.get(“/home/fred/readme.txt”); //Append to file Writer writer = Files.newBufferedWriter(file , StandardCharset.UTF_8 , StandardOpenOption.WRITE , StandardOpenOption.APPEND); 7 7
  • 8. File Operation – Copy, Move •  File copy is really easy –  With fine grain control Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/copy_readme.txt”); Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); •  File move is supported –  Optional atomic move supported Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/readme.1st”); Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE); 8 8
  • 9. File Operation – Links •  Hard and symbolic/soft links optionally supported •  API based on long standing Unix semantics •  Windows Vista or newer with NTFS •  File operations on symbolic links are followed by default except •  delete, move, walkFileTree •  Creating hard link Path src = Paths.get(“/home/fred/readme.txt”); Path linkFile = Paths.get(“/home/fred/readme.lnk”); Files.createLink(linkFile, src); •  Creating symbolic/soft link Files.createSymbolicLink(linkFile, src); 9 9
  • 10. Directories •  DirectoryStream iterate over entries –  Scales to large directories –  Uses less resources –  Smooth out response time for remote file systems –  Implements Iterable and Closeable for productivity •  Filtering support –  Build-in support for glob, regex and custom filters Path srcPath = Paths.get(“/home/fred/src”); try (DirectoryStream<Path> dir = srcPath.newDirectoryStream(“*.java”)) { for (Path file: dir) System.out.println(file.getName()); } 10 10
  • 11. Recursive Operation •  Interator to walk a file tree from a given starting point •  FileVisitor invoked for each file/directory encountered –  Based on visitor pattern •  Depth first, invoked twice for each directory (pre/post) •  Easy to develop recursive operations public interface FileVisitor<T> { FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs); FileVisitResult visitFile(T file, BasicFileAttributes attrs); FileVisitResult visitFileFailed(T file, IOException ex); FileVisitResult postVisitDirectory(T dir, IOException ex); } 11 11
  • 12. FileVisitor Example public class DeleteTildaFile extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { if (file.toFile().getName().endsWith(“~”)) Files.delete(file); return (FileVisitResult.CONTINUE); } } Path src = Paths.get(“/home/fred/src”); Files.walkFileTree(src, new DeleteTildaFile()); 12 12
  • 13. File Attributes •  Meta-data associated with file –  File owner, permissions, timestamps, DOS attributes, extended attributes –  Diverse and highly platform/file system specific •  Approach: group related attributes –  Providing typesafe and bulk access public interface PosixFileAttribute extends BasicFileAttribute { UserPrincipal owner(); GroupPrincipal group(); Set<PosixFilePermission> permissions(); } •  Views to access these attributes –  POSIX, ACL, DOS, extended, user defined, etc 13 13
  • 14. File Attributes – Read, Set, Query •  Reading file attributes PosixFileAttributeView view = Files.getFileAttributeView( file, PosixFileAttributeView.class); PosixFileAttributes attr = view.readAttributes(); System.out.println(“file owner = “ + attr.owner()); •  Setting file attributes Set<PosixFilePermission> perms = PosixFilePermissions .fromString(“rw-r-----”); Files.setPosixFilePermissions(file, perms); •  Querying supported attribute views Set<String> views = FileSystems.getDefault() .supportedFileAttributeViews(); 14 14
  • 15. File Change Notifications •  Watch files and directories for changes –  Typically polled •  WatchService –  Watches registered objects for changes and events –  Makes use of native event notification facility where possible –  Monitors directories, generates events when files are created, deleted or modified –  Extendable to other objects and events –  Deliberately a low level interface 15 15
  • 16. Major Classes •  WatchService –  Watches registered objects for changes and events –  Allows multiple threads to poll/take events •  Watchable –  An object that is registered with WatchService –  Implemented by Path •  WatchKey –  An object representing a registration •  WatchEvent –  An event 16 16
  • 17. WatchService Example •  Registering a WatchService WatchService watcher = FileSystems.getDefault().newWatchService(); Path tmp = Paths.get(“/home/fred/tmp”); tmp.register(watcher, StandardWatchEventKinds.ENTRY_CREATE , StandardWatchEventKinds.ENTRY_DELETE); •  Retrieving and processing events while (true) { WatchKey key = watcher.take(); //non-blocking – poll() for (WatchEvent<?> event: key.pollEvents()) { if (StandardWatchEventKinds.ENTRY_CREATE == event.kind() { Path newFile = (Path)event.context(); ... } } key.reset(); } 17 17
  • 18. FileSystem and FileStore •  FileSystem is an interface to a file system –  Also factory for files and other objects •  Retrieving the default filesystem FileSystem fs = FileSystems.getDefault(); •  Creating new file systems – eg. ZIP/JAR file system Map<String, String> attrs = new HashMap<>(); attrs.put(“create”, “true”); FileSystem zipfs = FileSystems.newFileSystems( “jar:file:/opt/tmp/myzip.zip”, attrs); •  FileStore represents storage devices –  Storage pools, partitions, volumes, etc •  Provider interface to implement new file system type 18 18
  • 19. Asynchronous I/O •  java.io a short history –  Pre JDK 1.4 – blocking I/O –  JDK 1.4 onwards – non blocking I/O, memory mapped files, file lock, channels and buffers –  JDK 7 – asynchronous I/O •  Provides asynchronous I/O to both sockets and files –  Take advantage of operating systems I/O facilities where available •  Programming styles –  Polling – I/O returns a Future object •  Poll to test for I/O completion –  Callback – specify a CompletionHandler when performing I/O •  CompletionHandler invoked when I/O completes or fails 19 19
  • 20. Asynchronous I/O – Example AsynchronousSocketChannel chan = AsynchronousSocketChannel.open(); //Non blocking connect/SOCK_NONBLOCK – polling Future<Void> result = chan.connect(new InetSocketAddress(...)); //Perform some operation until done result.isDone() result.get(); ByteBuffer buff = ByteBuffer.allocate(EIGHT_K); //Perform the read – callback chan.read(buff, buff, new MyCompletionHandler()); 20 20
  • 21. Asynchronous I/O – Example pubilc class MyCompletionHandler implements CompletionHandler<Integer, ByteBuffer> { //Invoked when operation is completed public void completed(Integer result, ByteBuffer buff) { ... } //Invoked when operation fails public void failed(Throwable ex, ByteBuffer buff) { ... } } 21 21
  • 22. Concurrency APIs •  JSR166y •  Update to JSR166x which was an update to JSR166 •  Adds a lightweight task framework •  Also referred to as Fork/Join •  Phaser •  Barrier similar to CyclicBarrier and CountDownLatch 22 22
  • 23. Fork Join Framework •  Goal is to take advantage of multiple processor •  Designed for task that can be broken down into smaller pieces –  Eg. Fibonacci number fib(10) = fib(9) + fib(8) •  Typical algorithm that uses fork join if I can manage the task perform the task else fork task into x number of smaller/similar task join the results 23 23
  • 24. Key Classes •  ForkJoinPool –  Executor service for running ForkJoinTask •  ForkJoinTask –  The base class for forkjoin task •  RecursiveAction –  A subclass of ForkJoinTask –  A recursive resultless task –  Implements compute() abstract method to perform calculation •  RecursiveTask –  Similar to RecursiveAction but returns a result 24 24
  • 25. ForkJoin Example – Fibonacci public class Fibonacci extends RecursiveTask<Integer> { private final int number; public Fibonacci(int n) { number = n; } @Override protected Integer compute() { switch (number) { case 0: return (0); case 1: return (1); default: Fibonacci f1 = new Fibonacci(number – 1); Fibonacci f2 = new Fibonacci(number – 2); f1.fork(); f2.fork(); return (f1.join() + f2.join()); } } } 25 25
  • 26. ForkJoin Example – Fibonacci ForkJoinPool pool = new ForkJoinPool(); Fibonacci r = new Fibonacci(10); pool.submit(r); while (!r.isDone()) { //Do some work ... } System.out.println("Result of fib(10) = “ + r.get()); 26 26
  • 27. Collections Updates •  TransferQueue interface •  Extension to BlockingQueue •  Implemented by LinkedTransferQueue •  Producers may, or may not, wait for consumer to receive element •  Can be capacity bounded or unbounded 27 27
  • 28. Client Libraries •  Nimbus Look and Feel •  Platform APIs for shaped and translucent windows •  JLayer (formerly from Swing labs) •  Optimised 2D rendering 28 28
  • 29. Shaped and Translucent Windows •  Uniform translucency •  Gradient translucency •  Shaped 29 29
  • 30. Shaped Window Example public class ShapedWindow extends JFrame { public ShapedWindow() { super("ShapedWindow"); addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { setShape( new Ellipse2D.Double(0,0, getWidth(),getHeight())); } }); setUndecorated(true); } } 30 30
  • 31. Nimbus Look and Feel •  Better than Metal for cross platform look-and-feel •  Introduced in Java SE 6u10, now part of Swing •  Not the default L&F 31 31
  • 32. JLayer and LayerUI •  A decorator for Swing components –  Layer on top of JPanel instead of using GlassPane –  Paint on Swing components without subclassing the component –  Can intercept AWT events •  LayerUI performs the painting and event processing 32 32
  • 33. LayerUI in Detail •  Extend and typically override the following •  paint(Graphics, JComponent) – draw on the component •  installUI(JComponent) – configure the component eg. setting the event mask •  processXXXEvent – process events (mouse, keyboard, etc) 33 33
  • 34. JLayer Example public class MyDecorator extends LayerUI<JPanel> { @Override public void installUI(JComponent c) { super.installUI(c); JLayer l = (JLayer)c; l.setLayerEventMask(AWTEvent.KEY_EVENT_MASK); } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D)g; //Draw on g2d ... } } 34 34
  • 35. JLayer Example //Create panel JPanel myPanel = ... MyDecorator myDecorator = new MyDecorator(); JLayer<JPanel> jLayer = new Jlayer<JPanel>(myPanel, myDecorator); 35 35
  • 36. JDBC 4.1 Changes •  Allow Connection, ResultSet and Statement objects to be used with the try-with-resources statement •  Implement AutoCloseable interface •  RowSetFactory and RowSetProvider classes added to javax.sql.rowset package 36 36
  • 37. Java APIs for XML •  JAXP 1.4.5 (Parsing) •  Bug fixes, conformance, security, performance •  StAX upgraded to version 1.2 •  JAXB 2.2.3 (Binding) •  Minor changes to XMLElement interface •  JAX-WS 2.2.4 (Web Services) •  Minor changes •  Support for Async Servlet Transport using Servlet 3.0 API 37 37
  • 38. java.util.Objects •  Utility methods for operating on objects –  Methods are null safe and null tolerant •  Objects.deepEquals(Object a, Object b) –  Deep equals •  Objects.hashCode(Object o) –  Return hash code of non-null argument or 0 for null argument •  Objects.requireNonNull(T o) –  Throws NullPointerException if o is null 38 38
  • 39. Conclusions •  Java SE 7 provides useful new APIs •  File handling APIs make routine tasks much simpler •  Fork-join framework simplifies concurrent decomposition of large tasks •  Many other useful features •  Java continues to deliver features developers require 39 39
  • 40. 40 40