27
Georgian Micsa What's new in JAVA

What`s new in Java 7

Embed Size (px)

DESCRIPTION

New features in: 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

Citation preview

Page 1: What`s new in Java 7

Georgian Micsa

What's new in

JAVA

Page 2: What`s new in Java 7

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

- [email protected]

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

Page 3: What`s new in Java 7

3

Agenda

Java 7 new features

Future Java 8

Java timeline

References

Page 4: What`s new in Java 7

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, 2002Assert, 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

Page 5: What`s new in Java 7

5

New features in Java 7

1. Java programming language2. Java I/O3. Concurrency4. Swing5. Networking6. Security7. Collections8. RIA9. Java 2D10. JDBC 4.111. JVM12. java.lang package13. Java XML14. I18N

Page 6: What`s new in Java 7

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);

Page 7: What`s new in Java 7

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);

Page 8: What`s new in Java 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"); }

Page 9: What`s new in Java 7

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<>();

Page 10: What`s new in Java 7

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); } }

Page 11: What`s new in Java 7

11

1. Java programming language

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

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

Page 12: What`s new in Java 7

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/Oand 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

Page 13: What`s new in Java 7

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();….

Page 14: What`s new in Java 7

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,

Page 15: What`s new in Java 7

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);

Page 16: What`s new in Java 7

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.

Page 17: What`s new in Java 7

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 windowsw.setShape(new Ellipse2D.Double(0,0,getWidth(),getHeight()));

- An HSV tab has been added to the JColorChooser class

Page 18: What`s new in Java 7

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.1bind 192.0.2.1 *# Use SDP when connecting to all application services on 192.0.2.*connect 192.0.2.0/24 1024-*

Page 19: What`s new in Java 7

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

Page 20: What`s new in Java 7

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

Page 21: What`s new in Java 7

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

Page 22: What`s new in Java 7

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

Page 23: What`s new in Java 7

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

Page 24: What`s new in Java 7

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” methodGarbage-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 targetsJava 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

Page 25: What`s new in Java 7

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

Page 26: What`s new in Java 7

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

Page 27: What`s new in Java 7

27

ReferencesJava Timeline:http://www.oracle.com/technetwork/java/javase/overview/javahistory-timeline-

198369.htmlJava 7:http://download.oracle.com/javase/7/docs/NIO 2:http://openjdk.java.net/projects/nio/presentations/TS-5686.pdfhttp://openjdk.java.net/projects/nio/presentations/TS-4222.pdfhttp://openjdk.java.net/projects/nio/presentations/TS-5052.pdfSWING:http://download.oracle.com/javase/tutorial/uiswing/misc/jlayer.htmlNetworking:http://download.oracle.com/javase/tutorial/sdp/sockets/index.htmlJVM:http://download.oracle.com/javase/7/docs/technotes/guides/vm/multiple-language-

support.htmlhttp://download.oracle.com/javase/7/docs/technotes/guides/vm/performance-

enhancements-7.htmlJava 8:http://jcp.org/en/jsr/detail?id=337