SlideShare a Scribd company logo
Javase7 1641812
<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

More Related Content

PPTX
Clean Sweep FileSystem - Java NIO 2
PDF
D Space Installation
PDF
Improving DSpace Backups, Restores & Migrations
PDF
DSpace: Technical Basics
PDF
Introduction to DSpace
PPT
DSpace Tutorial : Open Source Digital Library
PPTX
Hadoop
PPTX
DSpace 4.2 Transmission: Import/Export
Clean Sweep FileSystem - Java NIO 2
D Space Installation
Improving DSpace Backups, Restores & Migrations
DSpace: Technical Basics
Introduction to DSpace
DSpace Tutorial : Open Source Digital Library
Hadoop
DSpace 4.2 Transmission: Import/Export

What's hot (19)

PPT
Persistences
DOCX
Content server installation guide
PDF
Android Data Persistence
PPTX
PDF
Android Data Persistence
PDF
Fuse'ing python for rapid development of storage efficient FS
PPTX
DSpace 4.2 Basics & Configuration
PDF
XOOPS 2.6.0 Service Manager
KEY
Introduction to YUI PHP Loader
PPT
Hibernate java and_oracle
PPTX
Dspace software
PPTX
JSON in Solr: from top to bottom
PPT
eZ Publish cluster unleashed revisited
PDF
OOP Adventures with XOOPS
PPTX
SBT by Aform Research, Saulius Valatka
PDF
DSpace Manual for BALID Trainee
PDF
InfiniFlux collector
PDF
2-5-14 “DSpace User Interface Innovation” Presentation Slides
PDF
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
Persistences
Content server installation guide
Android Data Persistence
Android Data Persistence
Fuse'ing python for rapid development of storage efficient FS
DSpace 4.2 Basics & Configuration
XOOPS 2.6.0 Service Manager
Introduction to YUI PHP Loader
Hibernate java and_oracle
Dspace software
JSON in Solr: from top to bottom
eZ Publish cluster unleashed revisited
OOP Adventures with XOOPS
SBT by Aform Research, Saulius Valatka
DSpace Manual for BALID Trainee
InfiniFlux collector
2-5-14 “DSpace User Interface Innovation” Presentation Slides
What's new in TYPO3 6.2 LTS - #certiFUNcation Alumni Event 05.06.2015
Ad

Similar to Javase7 1641812 (20)

PDF
55 new things in Java 7 - Devoxx France
PDF
What`s new in Java 7
PPTX
Java se7 features
ODP
Java 7 Features and Enhancements
PPTX
Input/Output Exploring java.io
PPTX
Use of Apache Commons and Utilities
PPT
Jug java7
PDF
PDF
My History
PDF
Basic i/o & file handling in java
PDF
Java7 New Features and Code Examples
PPTX
Featuring JDK 7 Nio 2
PPT
Java Input Output and File Handling
PDF
Introducing the Java NIO.2
KEY
Back to the future with Java 7 (Geekout June/2011)
PDF
File Handling in Java.pdf
PPT
operating system File - System Interface
PDF
Synthesizing API Usage Examples
PPTX
55 new things in Java 7 - Devoxx France
What`s new in Java 7
Java se7 features
Java 7 Features and Enhancements
Input/Output Exploring java.io
Use of Apache Commons and Utilities
Jug java7
My History
Basic i/o & file handling in java
Java7 New Features and Code Examples
Featuring JDK 7 Nio 2
Java Input Output and File Handling
Introducing the Java NIO.2
Back to the future with Java 7 (Geekout June/2011)
File Handling in Java.pdf
operating system File - System Interface
Synthesizing API Usage Examples
Ad

More from Vinay H G (12)

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

Recently uploaded (20)

PPTX
A Presentation on Artificial Intelligence
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Getting Started with Data Integration: FME Form 101
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Machine Learning_overview_presentation.pptx
PDF
Encapsulation theory and applications.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
A Presentation on Artificial Intelligence
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Unlocking AI with Model Context Protocol (MCP)
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Network Security Unit 5.pdf for BCA BBA.
MYSQL Presentation for SQL database connectivity
Getting Started with Data Integration: FME Form 101
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation_ Review paper, used for researhc scholars
Machine Learning_overview_presentation.pptx
Encapsulation theory and applications.pdf
MIND Revenue Release Quarter 2 2025 Press Release
The Rise and Fall of 3GPP – Time for a Sabbatical?
Dropbox Q2 2025 Financial Results & Investor Presentation

Javase7 1641812

  • 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