SlideShare une entreprise Scribd logo
1  sur  27
Télécharger pour lire hors ligne
What's new in
   JAVA




                Georgian Micsa
About me

   Georgian Micsa

   - Software engineer with 5+ years of experience,
   mainly Java but also .NET and JavaScript
   - Interested in OOP, OOD and agile software development
   methodologies
   - Currently working as a senior Java developer @ Cegeka

   - georgian.micsa@gmail.com

   - http://ro.linkedin.com/in/georgianmicsa




                                                             2
Agenda


     Java timeline

     Java 7 new features

     Future Java 8

     References




                           3
Java timeline

   1.0 – January 23, 1996
   1.1 – February 19, 1997
       Inner classes, JavaBeans, JDBC, RMI, reflection
   1.2 – December 8, 1998
       Strictfp, Swing, JIT compiler, Java IDL, Collections
   1.3 – May 8, 2000
       HotSpot JVM, JavaSound, JNDI, JPDA, proxies
   1.4 – February 6, 2002
       Assert, regex, IPv6, NIO, logger, ImageIO, JAXP, JCE, Java Web Start
   5 – September 30, 2004
       Generics, annotations, auto/unboxing, enum, varargs, foreach loop, static imports,
  skinnable look and feel called Synth, java.util.concurrent, Scanner class
   6 – December 11, 2006
        Scripting language support, performance improvements for Swing, JAX-WS, JDBC 4.0,
  StAX, SwingWorker, table sorting and filtering, double-buffering, JVM improvements, Java Quick
  Starter, Java2D uses Direct3D on Windows, Nimbus L&F




                                                                                             4
New features in Java 7
   1. Java programming language
   2. Java I/O
   3. Concurrency
   4. Swing
   5. Networking
   6. Security
   7. Collections
   8. RIA
   9. Java 2D
   10. JDBC 4.1
   11. JVM
   12. java.lang package
   13. Java XML
   14. I18N

                                  5
1. Java programming language
 Binary Literals:

    // An 8-bit 'byte' value:
    byte aByte = (byte) 0b00100001;

    // A 16-bit 'short' value:
    short aShort = (short) 0b1010000101000101;

    // Some 32-bit 'int' values:
    int anInt1 = 0b10100001010001011010000101000101;
    int anInt2 = 0b101;
    int anInt3 = 0B101; // The B can be upper or lower case.

    // A 64-bit 'long' value. Note the "L" suffix:
    long aLong = 0b1000000000000000000001L;

    System.out.println(aLong);




                                                               6
1. Java programming language

  Underscores in Numeric Literals:

     long creditCardNumber = 1234_5678_9012_3456L;
     long socialSecurityNumber = 999_99_9999L;
     float pi = 3.14_15F;
     long hexBytes = 0xFF_EC_DE_5E;
     long hexWords = 0xCAFE_BABE;
     long maxLong = 0x7fff_ffff_ffff_ffffL;
     byte nybbles = 0b0010_0101;
     long bytes = 0b11010010_01101001_10010100_10010010;

     System.out.println(creditCardNumber);




                                                           7
1. Java programming language

 Strings in Switch Statements:

    String myString = "tiger";
    switch (myString) {
       case "crocodile":
         System.out.println("Watch out! It`s a reptile!");
         break;
       case "tiger":
       case "lion":
         System.out.println("Watch out! It`s a cat!");
         break;
       default:
         System.out.println("Sorry...Animal not identified");
    }




                                                                8
1. Java programming language

 Type Inference for Generic Instance Creation:

 //before 7
       Map<String, List<String>> myMap = new HashMap<String, List<String>>();


 // DIAMOND operator
 //after 7
       Map<String, List<String>> myMap2 = new HashMap<>();




                                                                                9
1. Java programming language

Automatic Resource Management (ARM):
- Also known as 'try-with-resources' statement
- Resources must implement interface AutoClosable

   try (ZipFile zf = new ZipFile("test.zip");
         FileInputStream fis = new FileInputStream("test.zip");) {

       for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
          String zipEntryName = ((java.util.zip.ZipEntry) entries.nextElement()).getName();
          System.out.println(zipEntryName);
       }
   }




                                                                                              10
1. Java programming language

 Handling more than one type of exception:
 // before 7
 catch (IOException ex) {
     logger.log(ex);
     throw ex;
 catch (SQLException ex) {
     logger.log(ex);
     throw ex;
 }

 // after 7
 catch (IOException|SQLException ex) {
     logger.log(ex);
     throw ex;
 }




                                             11
2. Java I/O
 - Completely refactored I/O with better performance
 - Packages java.nio.file and java.nio.file.attribute: comprehensive support for file I/O
 and for accessing the default file system
 - The Path class:
       Path p1 = Paths.get("/tmp/foo");
       Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
       Path p5 = Paths.get(System.getProperty("user.home"), "logs", "foo.log");
 - Checking files: Files.isRegularFile(path); isReadable(path); isExecutable(path); isDirectory(path);
 isHidden(path); size(path); getOwner(); etc.
 - Delete file or directory: Files.delete(path);
 - Copy file or dir: Files.copy(source, target, REPLACE_EXISTING);
 - Move/rename file or dir: Files.move(source, target, REPLACE_EXISTING);
 - Read file: fileArray = Files.readAllBytes(path);
 - Create file: pathFile.newOutputStream(CREATE, APPEND); Files.createFile(path);
 - Random access: interface SeekableByteChannel
 - The FileSystems class: FileSystems.getDefault().getFileStores()
 - Links: Files.createSymbolicLink(newLink, target); Files.createLink(newLink, existingFile);
 - Walking the file tree: the FileVisitor interface
 - Finding files: FileSystems.getDefault().getPathMatcher("glob:*.{java,class}");
 - Coexistence with legacy code: Path input = file.toPath();
 - Custom File System Providers: ex. JAR file system provider
                                                                                              12
2. Java I/O
  Directory Watch Service:
      WatchService watcher = FileSystems.getDefault().newWatchService();
      WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
  StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
      for (;;) {
         //wait for key to be signaled
         try {
             key = watcher.take();
         } catch (InterruptedException x) {
             return;
         }

        for (WatchEvent<?> event : key.pollEvents()) {
           WatchEvent.Kind<?> kind = event.kind();

          //This key is registered only for ENTRY_CREATE events,
          //but an OVERFLOW event can occur regardless if events are
          //lost or discarded.
          if (kind == StandardWatchEventKinds.OVERFLOW) {
              continue;
          }

          //The filename is the context of the event.
          WatchEvent<Path> ev = (WatchEvent<Path>) event;
          Path filename = ev.context();
  ….


                                                                                   13
2. Java I/O
  Non-blocking I/O or asynchronous I/O:

  A. Return Future representing pending result:

  AsynchronousSocketChannel ch = ...
  Future<Integer> result = ch.read(buf);
  int nread = result.get();
  B. CompletionHandler invoked when I/O completes:

  interface CompletionHandler<V,A> {
         void completed(V result, A attachment);
         void failed(Throwable exc, A attachment);
  }
  ch.read(buf, conn, handler);


  - New classes: AsynchronousSocketChannel, AsynchronousServerSocketChannel,
  AsynchronousDatagramChannel, AsynchronousFileChannel

  - Async operations: READ/WRITE, CONNECT, ACCEPT, RECEIVE/SEND,




                                                                               14
3. Concurrency
  Fork-join framework:
  - parallel programming
  - based on the ForkJoinPool class (Executor)
  - work-stealing technique for the workers
  - divide and conquer problems: RecursiveTask and RecursiveAction classes

  class ForkSum extends RecursiveTask<Long> {
       @Override
       protected Long compute() {
         if (toIndex - fromIndex <= DIRECT_COMPUTE_SIZE) {
             return computeDirectly();
         }
         int split = (fromIndex + toIndex) / 2;
         ForkSum f1 = new ForkSum(array, fromIndex, split);
         f1.fork();
         ForkSum f2 = new ForkSum(array, split + 1, toIndex);
         f2.fork();
         return f2.join() + f1.join();
  }

  //MAIN:
        ForkSum forkSum = new ForkSum(computeArray, 0, N - 1);
        ForkJoinPool pool = new ForkJoinPool(); // uses number of cores
        Long result = pool.invoke(forkSum);




                                                                             15
3. Concurrency

- The ThreadLocalRandom class eliminates contention among threads using pseudo-random numbers
- For concurrent access (fork-join framework), using ThreadLocalRandom instead of Math.random()
 results in less contention and, ultimately, better performance.

int r = ThreadLocalRandom.current().nextInt(4, 77);


- The Phaser class is a new synchronization barrier, similar to CyclicBarrier
- More flexible usage
- Number of parties registered to synchronize on a phaser may vary over time: register(), bulkRegister(),
 arriveAndDeregister();
- Better synchronization: arriveAndAwaitAdvance(), arrive(), arriveAndDeregister(),
awaitAdvance(int phase)
- Termination: isTerminated(), forceTermination()
- Monitoring: getRegisteredParties(), getArrivedParties(), getPhase(), getUnarrivedParties()
- Tiering: Build phasers in tree structure to reduce contention.




                                                                                                16
4. Swing
- The JLayer class has been added, which is a flexible and powerful decorator for Swing components
- You can draw effects, blurring, animating a busy indicator, validate textfields, respond to events etc.
     JFrame f = new JFrame();
     JPanel panel = createPanel();
     LayerUI<JPanel> layerUI = new WallpaperLayerUI();
     JLayer<JPanel> jlayer = new JLayer<JPanel>(panel, layerUI);
     f.add (jlayer);

     class WallpaperLayerUI extends LayerUI<JComponent> {
           public void paint(Graphics g, JComponent c) {
           ...
           }
     }


- The Nimbus Look and Feel has been moved from the com.sun.java.swing package
to the javax.swing package
- Mixing Heavyweight and Lightweight Components is easier to accomplish
- Windows with transparency and non-rectangular shape are supported
           // Set the window to 55% opaque (45% translucent).
           w.setOpacity(0.55f);
           // Shaped windows
           w.setShape(new Ellipse2D.Double(0,0,getWidth(),getHeight()));
- An HSV tab has been added to the JColorChooser class

                                                                                                17
5. Networking
 - The URLClassLoader.close() method has been added
 - Invalidates the loader
 - It also closes any JAR files - this allows the application to delete or replace these files


 - The Sockets Direct Protocol (SDP) provides access to high performance network connections
 - Introduced in 1999 by the InfiniBand Trade Association,
 InfiniBand (IB) was created to address the need for high performance computing
 - Remote Direct Memory Access (RDMA):
       - enables moving data directly from the memory of one computer to another computer
       - bypassing the operating system of both computers
       - resulting in significant performance gains
 - SDP supports stream connections over InfiniBand fabric
 - No API changes required in JDK
 - The implementation of SDP is transparent and supported by the classic networking and new I/O
 - You only have to create a configuration file. Example:
      # Use SDP when binding to 192.0.2.1
      bind 192.0.2.1 *
      # Use SDP when connecting to all application services on 192.0.2.*
      connect 192.0.2.0/24 1024-*



                                                                                                 18
6. Security

- Support for Elliptic Curve Cryptography (ECC)

- A new native provider has been added that provides several ECC-based algorithms (ECDSA/ECDH):
     - DSA Signatures using ECC
     - Key agreement: Diffie-Hellman key exchange using ECC


- Weak cryptographic algorithms can now be disabled, for example MD2


- Various enhancements related to SSL/TLS have been added to Java Secure Socket Extension




                                                                                       19
7. Collections

  - The TransferQueue interface has been added
  - A refinement of the BlockingQueue interface:
             - producers may wait for consumers to receive elements
                  -     transfer(E e)
                  -     tryTransfer(E e)
                  -     tryTransfer(E e, long timeout, TimeUnit unit)
             - getWaitingConsumerCount()
             - hasWaitingConsumer()
  - The class LinkedTransferQueue implements the TransferQueue interface




                                                                           20
8. RIA

- The window of a dragged applet can be decorated with a default or custom title
- Enhancements have been made to the syntax of JNLP files:
     - The os attribute in the information and resources elements can now contain
     specific versions of Windows
     - Applications can use the install attribute in the shortcut element
     - Java Web Start applications can be deployed without specifying the codebase attribute
- A JNLP file can be embedded into an HTML page:
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
   var attributes = {} ;
   <!-- Base64 encoded string truncated below for readability -->
   var parameters = {jnlp_href: 'dynamictree-applet.jnlp',
      jnlp_embedded: 'PCEtLSAKLyoKICogQ29weX ... HA+Cg=='
   };
   deployJava.runApplet(attributes, parameters, '1.6');
</script>
- You can check the status variable of the applet while it is loading to determine
if the applet is ready to handle requests from JavaScript code




                                                                                          21
9. Java 2D

- A new XRender-based Java 2D rendering pipeline is supported for modern X11-based desktops,
 offering improved graphics performance:

         -Dsun.java2d.xrender=true

- The JDK now enumerates and displays installed OpenType/CFF fonts
 through methods such as GraphicsEnvironment.getAvailableFontFamilyNames




                                                                                       22
10. JDBC 4.1

- The ability to use a try-with-resources statement to automatically close
 resources of type Connection, ResultSet, and Statement:
 try (Statement stmt = con.createStatement()) {

     // ...

 }

- RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class
- Enable you to create all types of row sets supported by your JDBC driver
- JdbcRowSet:
     - enhanced ResultSet object
     - it maintains a connection to its data source
     - it has a set of properties and a listener notification mechanism
     - it makes a ResultSet object scrollable and updatable
- The RowSetFactory interface:
              - createCachedRowSet
              - createFilteredRowSet
              - createJdbcRowSet
              - createJoinRowSet
              - createWebRowSet




                                                                                       23
11. JVM
JVM Support for Non-Java Languages
- Dynamically typed language => type checking at runtime
- New JVM instruction that simplifies the implementation of dynamically typed
 programming languages on the JVM: invokedynamic
- Allows the language implementer to define custom linkage behavior
- Define bootstrap method that links the invokedynamic call site to the “real” method
Garbage-First Collector
- Server-style garbage collector that replaces the Concurrent Mark-Sweep Collector (CMS)
- Targeted for multi-processors with large memories, decrease pause times and increase throughput
- Marking and evacuation is performed on parallel on multi-processors
- G1 partitions the Heap in equal size regions and compacts them
- G1 first collects and compacts the regions full of reclaimable objects
- More predictable garbage collection pauses than CMS
- User can set the desired pause targets
Java HotSpot Virtual Machine Performance Enhancements
- Tiered Compilation => speed up the server VM: -server -XX:+TieredCompilation
- Compressed Oops – managed pointers for objects offsets and not byte offsets
- Escape analysis
      - compiler may eliminate certain object allocations
      - compiler may eliminate synchronization blocks (lock elision)
- NUMA Collector enhancements for the parallel GC
                                                                                         24
java.lang, XML & I18N

12. java.lang package
- Potential deadlocks were eliminated for multithreaded, non-hierarchically delegating
 custom class loaders

13. Java XML
- Java API for XML Processing (JAXP) 1.4.5,
- Java Architecture for XML Binding (JAXB) 2.2.3,
- Java API for XML Web Services (JAX-WS) 2.2.4

14. I18N
- Support for Unicode 6.0.0:
     - over 2000 additional characters, as well as support for properties and data files
     - by default in Java 1 char = 16 bits => only 65536 characters
      - supplementary characters are defined as a pair of char values, from 0x10000 to 0x10FFFF
- Extensible Support for ISO 4217 Currency Codes: currency.properties
- Category Locale Support: 2 types of category: Locale.Category FORMAT and DISPLAY
- Unicode 6.0 Support in Regular Expressions API



                                                                                          25
Future Java 8

 - Modularization of the JDK under Project Jigsaw
 - Parts of project Coin that are not included in Java 7
 - Language-level support for lambda expressions
 (officially, lambda expressions; unofficially, closures)
 under Project Lambda:
         Collection collection = ... ;
         collection.sortBy(#{ Foo f -> f.getLastName() });
         collection.remove(#{ Foo f -> f.isBlue() });
 - Annotations on Java Types:
     Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;
 - New Date and Time API




                                                                       26
References
  Java Timeline:
  http://www.oracle.com/technetwork/java/javase/overview/javahistory-timeline-
     198369.html
  Java 7:
  http://download.oracle.com/javase/7/docs/
  NIO 2:
  http://openjdk.java.net/projects/nio/presentations/TS-5686.pdf
  http://openjdk.java.net/projects/nio/presentations/TS-4222.pdf
  http://openjdk.java.net/projects/nio/presentations/TS-5052.pdf
  SWING:
  http://download.oracle.com/javase/tutorial/uiswing/misc/jlayer.html
  Networking:
  http://download.oracle.com/javase/tutorial/sdp/sockets/index.html
  JVM:
  http://download.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language-
     support.html
  http://download.oracle.com/javase/7/docs/technotes/guides/vm/performance-
     enhancements-7.html
  Java 8:
  http://jcp.org/en/jsr/detail?id=337


                                                                                    27

Contenu connexe

Tendances

Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
rahulrevo
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 

Tendances (20)

Java byte code in practice
Java byte code in practiceJava byte code in practice
Java byte code in practice
 
Making Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVMMaking Java more dynamic: runtime code generation for the JVM
Making Java more dynamic: runtime code generation for the JVM
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
JVM
JVMJVM
JVM
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java7 New Features and Code Examples
Java7 New Features and Code ExamplesJava7 New Features and Code Examples
Java7 New Features and Code Examples
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
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
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
An introduction to JVM performance
An introduction to JVM performanceAn introduction to JVM performance
An introduction to JVM performance
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 

En vedette

JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
José Paumard
 
Recommendation engines
Recommendation enginesRecommendation engines
Recommendation engines
Georgian Micsa
 

En vedette (19)

OCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certificationsOCAJP 7 and OCPJP 7 certifications
OCAJP 7 and OCPJP 7 certifications
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)
 
Recommendation engines
Recommendation enginesRecommendation engines
Recommendation engines
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
50 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 850 nouvelles choses que l'on peut faire avec Java 8
50 nouvelles choses que l'on peut faire avec Java 8
 
Java 8-streams-collectors-patterns
Java 8-streams-collectors-patternsJava 8-streams-collectors-patterns
Java 8-streams-collectors-patterns
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
50 new things you can do with java 8
50 new things you can do with java 850 new things you can do with java 8
50 new things you can do with java 8
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
API Asynchrones en Java 8
API Asynchrones en Java 8API Asynchrones en Java 8
API Asynchrones en Java 8
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Les Streams sont parmi nous
Les Streams sont parmi nousLes Streams sont parmi nous
Les Streams sont parmi nous
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 

Similaire à What`s new in Java 7

Java Intro
Java IntroJava Intro
Java Intro
backdoor
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 

Similaire à What`s new in Java 7 (20)

55j7
55j755j7
55j7
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France55 new things in Java 7 - Devoxx France
55 new things in Java 7 - Devoxx France
 
Java
JavaJava
Java
 
Modern Java Development
Modern Java DevelopmentModern Java Development
Modern Java Development
 
Apache ZooKeeper
Apache ZooKeeperApache ZooKeeper
Apache ZooKeeper
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Nantes Jug - Java 7
Nantes Jug - Java 7Nantes Jug - Java 7
Nantes Jug - Java 7
 
Node intro
Node introNode intro
Node intro
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
core java material.pdf
core java material.pdfcore java material.pdf
core java material.pdf
 
Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)Back to the future with Java 7 (Geekout June/2011)
Back to the future with Java 7 (Geekout June/2011)
 
Java Intro
Java IntroJava Intro
Java Intro
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Introduction to Apache Mesos
Introduction to Apache MesosIntroduction to Apache Mesos
Introduction to Apache Mesos
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
From Java 6 to Java 7 reference
From Java 6 to Java 7 referenceFrom Java 6 to Java 7 reference
From Java 6 to Java 7 reference
 
NodeJs
NodeJsNodeJs
NodeJs
 
Inside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUGInside the JVM - Follow the white rabbit! / Breizh JUG
Inside the JVM - Follow the white rabbit! / Breizh JUG
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

What`s new in Java 7

  • 1. What's new in JAVA Georgian Micsa
  • 2. About me Georgian Micsa - Software engineer with 5+ years of experience, mainly Java but also .NET and JavaScript - Interested in OOP, OOD and agile software development methodologies - Currently working as a senior Java developer @ Cegeka - georgian.micsa@gmail.com - http://ro.linkedin.com/in/georgianmicsa 2
  • 3. Agenda Java timeline Java 7 new features Future Java 8 References 3
  • 4. Java timeline 1.0 – January 23, 1996 1.1 – February 19, 1997 Inner classes, JavaBeans, JDBC, RMI, reflection 1.2 – December 8, 1998 Strictfp, Swing, JIT compiler, Java IDL, Collections 1.3 – May 8, 2000 HotSpot JVM, JavaSound, JNDI, JPDA, proxies 1.4 – February 6, 2002 Assert, regex, IPv6, NIO, logger, ImageIO, JAXP, JCE, Java Web Start 5 – September 30, 2004 Generics, annotations, auto/unboxing, enum, varargs, foreach loop, static imports, skinnable look and feel called Synth, java.util.concurrent, Scanner class 6 – December 11, 2006 Scripting language support, performance improvements for Swing, JAX-WS, JDBC 4.0, StAX, SwingWorker, table sorting and filtering, double-buffering, JVM improvements, Java Quick Starter, Java2D uses Direct3D on Windows, Nimbus L&F 4
  • 5. New features in Java 7 1. Java programming language 2. Java I/O 3. Concurrency 4. Swing 5. Networking 6. Security 7. Collections 8. RIA 9. Java 2D 10. JDBC 4.1 11. JVM 12. java.lang package 13. Java XML 14. I18N 5
  • 6. 1. Java programming language Binary Literals: // An 8-bit 'byte' value: byte aByte = (byte) 0b00100001; // A 16-bit 'short' value: short aShort = (short) 0b1010000101000101; // Some 32-bit 'int' values: int anInt1 = 0b10100001010001011010000101000101; int anInt2 = 0b101; int anInt3 = 0B101; // The B can be upper or lower case. // A 64-bit 'long' value. Note the "L" suffix: long aLong = 0b1000000000000000000001L; System.out.println(aLong); 6
  • 7. 1. Java programming language Underscores in Numeric Literals: long creditCardNumber = 1234_5678_9012_3456L; long socialSecurityNumber = 999_99_9999L; float pi = 3.14_15F; long hexBytes = 0xFF_EC_DE_5E; long hexWords = 0xCAFE_BABE; long maxLong = 0x7fff_ffff_ffff_ffffL; byte nybbles = 0b0010_0101; long bytes = 0b11010010_01101001_10010100_10010010; System.out.println(creditCardNumber); 7
  • 8. 1. Java programming language Strings in Switch Statements: String myString = "tiger"; switch (myString) { case "crocodile": System.out.println("Watch out! It`s a reptile!"); break; case "tiger": case "lion": System.out.println("Watch out! It`s a cat!"); break; default: System.out.println("Sorry...Animal not identified"); } 8
  • 9. 1. Java programming language Type Inference for Generic Instance Creation: //before 7 Map<String, List<String>> myMap = new HashMap<String, List<String>>(); // DIAMOND operator //after 7 Map<String, List<String>> myMap2 = new HashMap<>(); 9
  • 10. 1. Java programming language Automatic Resource Management (ARM): - Also known as 'try-with-resources' statement - Resources must implement interface AutoClosable try (ZipFile zf = new ZipFile("test.zip"); FileInputStream fis = new FileInputStream("test.zip");) { for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { String zipEntryName = ((java.util.zip.ZipEntry) entries.nextElement()).getName(); System.out.println(zipEntryName); } } 10
  • 11. 1. Java programming language Handling more than one type of exception: // before 7 catch (IOException ex) { logger.log(ex); throw ex; catch (SQLException ex) { logger.log(ex); throw ex; } // after 7 catch (IOException|SQLException ex) { logger.log(ex); throw ex; } 11
  • 12. 2. Java I/O - Completely refactored I/O with better performance - Packages java.nio.file and java.nio.file.attribute: comprehensive support for file I/O and for accessing the default file system - The Path class: Path p1 = Paths.get("/tmp/foo"); Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java")); Path p5 = Paths.get(System.getProperty("user.home"), "logs", "foo.log"); - Checking files: Files.isRegularFile(path); isReadable(path); isExecutable(path); isDirectory(path); isHidden(path); size(path); getOwner(); etc. - Delete file or directory: Files.delete(path); - Copy file or dir: Files.copy(source, target, REPLACE_EXISTING); - Move/rename file or dir: Files.move(source, target, REPLACE_EXISTING); - Read file: fileArray = Files.readAllBytes(path); - Create file: pathFile.newOutputStream(CREATE, APPEND); Files.createFile(path); - Random access: interface SeekableByteChannel - The FileSystems class: FileSystems.getDefault().getFileStores() - Links: Files.createSymbolicLink(newLink, target); Files.createLink(newLink, existingFile); - Walking the file tree: the FileVisitor interface - Finding files: FileSystems.getDefault().getPathMatcher("glob:*.{java,class}"); - Coexistence with legacy code: Path input = file.toPath(); - Custom File System Providers: ex. JAR file system provider 12
  • 13. 2. Java I/O Directory Watch Service: WatchService watcher = FileSystems.getDefault().newWatchService(); WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); for (;;) { //wait for key to be signaled try { key = watcher.take(); } catch (InterruptedException x) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); //This key is registered only for ENTRY_CREATE events, //but an OVERFLOW event can occur regardless if events are //lost or discarded. if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } //The filename is the context of the event. WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); …. 13
  • 14. 2. Java I/O Non-blocking I/O or asynchronous I/O: A. Return Future representing pending result: AsynchronousSocketChannel ch = ... Future<Integer> result = ch.read(buf); int nread = result.get(); B. CompletionHandler invoked when I/O completes: interface CompletionHandler<V,A> { void completed(V result, A attachment); void failed(Throwable exc, A attachment); } ch.read(buf, conn, handler); - New classes: AsynchronousSocketChannel, AsynchronousServerSocketChannel, AsynchronousDatagramChannel, AsynchronousFileChannel - Async operations: READ/WRITE, CONNECT, ACCEPT, RECEIVE/SEND, 14
  • 15. 3. Concurrency Fork-join framework: - parallel programming - based on the ForkJoinPool class (Executor) - work-stealing technique for the workers - divide and conquer problems: RecursiveTask and RecursiveAction classes class ForkSum extends RecursiveTask<Long> { @Override protected Long compute() { if (toIndex - fromIndex <= DIRECT_COMPUTE_SIZE) { return computeDirectly(); } int split = (fromIndex + toIndex) / 2; ForkSum f1 = new ForkSum(array, fromIndex, split); f1.fork(); ForkSum f2 = new ForkSum(array, split + 1, toIndex); f2.fork(); return f2.join() + f1.join(); } //MAIN: ForkSum forkSum = new ForkSum(computeArray, 0, N - 1); ForkJoinPool pool = new ForkJoinPool(); // uses number of cores Long result = pool.invoke(forkSum); 15
  • 16. 3. Concurrency - The ThreadLocalRandom class eliminates contention among threads using pseudo-random numbers - For concurrent access (fork-join framework), using ThreadLocalRandom instead of Math.random() results in less contention and, ultimately, better performance. int r = ThreadLocalRandom.current().nextInt(4, 77); - The Phaser class is a new synchronization barrier, similar to CyclicBarrier - More flexible usage - Number of parties registered to synchronize on a phaser may vary over time: register(), bulkRegister(), arriveAndDeregister(); - Better synchronization: arriveAndAwaitAdvance(), arrive(), arriveAndDeregister(), awaitAdvance(int phase) - Termination: isTerminated(), forceTermination() - Monitoring: getRegisteredParties(), getArrivedParties(), getPhase(), getUnarrivedParties() - Tiering: Build phasers in tree structure to reduce contention. 16
  • 17. 4. Swing - The JLayer class has been added, which is a flexible and powerful decorator for Swing components - You can draw effects, blurring, animating a busy indicator, validate textfields, respond to events etc. JFrame f = new JFrame(); JPanel panel = createPanel(); LayerUI<JPanel> layerUI = new WallpaperLayerUI(); JLayer<JPanel> jlayer = new JLayer<JPanel>(panel, layerUI); f.add (jlayer); class WallpaperLayerUI extends LayerUI<JComponent> { public void paint(Graphics g, JComponent c) { ... } } - The Nimbus Look and Feel has been moved from the com.sun.java.swing package to the javax.swing package - Mixing Heavyweight and Lightweight Components is easier to accomplish - Windows with transparency and non-rectangular shape are supported // Set the window to 55% opaque (45% translucent). w.setOpacity(0.55f); // Shaped windows w.setShape(new Ellipse2D.Double(0,0,getWidth(),getHeight())); - An HSV tab has been added to the JColorChooser class 17
  • 18. 5. Networking - The URLClassLoader.close() method has been added - Invalidates the loader - It also closes any JAR files - this allows the application to delete or replace these files - The Sockets Direct Protocol (SDP) provides access to high performance network connections - Introduced in 1999 by the InfiniBand Trade Association, InfiniBand (IB) was created to address the need for high performance computing - Remote Direct Memory Access (RDMA): - enables moving data directly from the memory of one computer to another computer - bypassing the operating system of both computers - resulting in significant performance gains - SDP supports stream connections over InfiniBand fabric - No API changes required in JDK - The implementation of SDP is transparent and supported by the classic networking and new I/O - You only have to create a configuration file. Example: # Use SDP when binding to 192.0.2.1 bind 192.0.2.1 * # Use SDP when connecting to all application services on 192.0.2.* connect 192.0.2.0/24 1024-* 18
  • 19. 6. Security - Support for Elliptic Curve Cryptography (ECC) - A new native provider has been added that provides several ECC-based algorithms (ECDSA/ECDH): - DSA Signatures using ECC - Key agreement: Diffie-Hellman key exchange using ECC - Weak cryptographic algorithms can now be disabled, for example MD2 - Various enhancements related to SSL/TLS have been added to Java Secure Socket Extension 19
  • 20. 7. Collections - The TransferQueue interface has been added - A refinement of the BlockingQueue interface: - producers may wait for consumers to receive elements - transfer(E e) - tryTransfer(E e) - tryTransfer(E e, long timeout, TimeUnit unit) - getWaitingConsumerCount() - hasWaitingConsumer() - The class LinkedTransferQueue implements the TransferQueue interface 20
  • 21. 8. RIA - The window of a dragged applet can be decorated with a default or custom title - Enhancements have been made to the syntax of JNLP files: - The os attribute in the information and resources elements can now contain specific versions of Windows - Applications can use the install attribute in the shortcut element - Java Web Start applications can be deployed without specifying the codebase attribute - A JNLP file can be embedded into an HTML page: <script src="http://www.java.com/js/deployJava.js"></script> <script> var attributes = {} ; <!-- Base64 encoded string truncated below for readability --> var parameters = {jnlp_href: 'dynamictree-applet.jnlp', jnlp_embedded: 'PCEtLSAKLyoKICogQ29weX ... HA+Cg==' }; deployJava.runApplet(attributes, parameters, '1.6'); </script> - You can check the status variable of the applet while it is loading to determine if the applet is ready to handle requests from JavaScript code 21
  • 22. 9. Java 2D - A new XRender-based Java 2D rendering pipeline is supported for modern X11-based desktops, offering improved graphics performance: -Dsun.java2d.xrender=true - The JDK now enumerates and displays installed OpenType/CFF fonts through methods such as GraphicsEnvironment.getAvailableFontFamilyNames 22
  • 23. 10. JDBC 4.1 - The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement: try (Statement stmt = con.createStatement()) { // ... } - RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class - Enable you to create all types of row sets supported by your JDBC driver - JdbcRowSet: - enhanced ResultSet object - it maintains a connection to its data source - it has a set of properties and a listener notification mechanism - it makes a ResultSet object scrollable and updatable - The RowSetFactory interface: - createCachedRowSet - createFilteredRowSet - createJdbcRowSet - createJoinRowSet - createWebRowSet 23
  • 24. 11. JVM JVM Support for Non-Java Languages - Dynamically typed language => type checking at runtime - New JVM instruction that simplifies the implementation of dynamically typed programming languages on the JVM: invokedynamic - Allows the language implementer to define custom linkage behavior - Define bootstrap method that links the invokedynamic call site to the “real” method Garbage-First Collector - Server-style garbage collector that replaces the Concurrent Mark-Sweep Collector (CMS) - Targeted for multi-processors with large memories, decrease pause times and increase throughput - Marking and evacuation is performed on parallel on multi-processors - G1 partitions the Heap in equal size regions and compacts them - G1 first collects and compacts the regions full of reclaimable objects - More predictable garbage collection pauses than CMS - User can set the desired pause targets Java HotSpot Virtual Machine Performance Enhancements - Tiered Compilation => speed up the server VM: -server -XX:+TieredCompilation - Compressed Oops – managed pointers for objects offsets and not byte offsets - Escape analysis - compiler may eliminate certain object allocations - compiler may eliminate synchronization blocks (lock elision) - NUMA Collector enhancements for the parallel GC 24
  • 25. java.lang, XML & I18N 12. java.lang package - Potential deadlocks were eliminated for multithreaded, non-hierarchically delegating custom class loaders 13. Java XML - Java API for XML Processing (JAXP) 1.4.5, - Java Architecture for XML Binding (JAXB) 2.2.3, - Java API for XML Web Services (JAX-WS) 2.2.4 14. I18N - Support for Unicode 6.0.0: - over 2000 additional characters, as well as support for properties and data files - by default in Java 1 char = 16 bits => only 65536 characters - supplementary characters are defined as a pair of char values, from 0x10000 to 0x10FFFF - Extensible Support for ISO 4217 Currency Codes: currency.properties - Category Locale Support: 2 types of category: Locale.Category FORMAT and DISPLAY - Unicode 6.0 Support in Regular Expressions API 25
  • 26. Future Java 8 - Modularization of the JDK under Project Jigsaw - Parts of project Coin that are not included in Java 7 - Language-level support for lambda expressions (officially, lambda expressions; unofficially, closures) under Project Lambda: Collection collection = ... ; collection.sortBy(#{ Foo f -> f.getLastName() }); collection.remove(#{ Foo f -> f.isBlue() }); - Annotations on Java Types: Map<@NonNull String, @NonEmpty List<@Readonly Document>> files; - New Date and Time API 26
  • 27. References Java Timeline: http://www.oracle.com/technetwork/java/javase/overview/javahistory-timeline- 198369.html Java 7: http://download.oracle.com/javase/7/docs/ NIO 2: http://openjdk.java.net/projects/nio/presentations/TS-5686.pdf http://openjdk.java.net/projects/nio/presentations/TS-4222.pdf http://openjdk.java.net/projects/nio/presentations/TS-5052.pdf SWING: http://download.oracle.com/javase/tutorial/uiswing/misc/jlayer.html Networking: http://download.oracle.com/javase/tutorial/sdp/sockets/index.html JVM: http://download.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language- support.html http://download.oracle.com/javase/7/docs/technotes/guides/vm/performance- enhancements-7.html Java 8: http://jcp.org/en/jsr/detail?id=337 27