55 new features in java 7
DESCRIPTION
Presented at BJUG, 6/12/2012 by Roger Brinkley This talk is on 55 new features in Java 7 you (probably) didn't hear about in an ignite format of one per minute. No stopping, no going back....Questions, sure but only if time remains (otherwise save for later).TRANSCRIPT
![Page 1: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/1.jpg)
11
The 55 New Java 7 Features You (Probably) Didn't Hear About
• 55 minutes – 55 slides• Ignite Format
• No stopping!• No going back!• Questions? Sure, but only if and until time remains on slide
(otherwise, save for later)
• The PRD for Java 7 had almost 2000 changes, here are 55 of the more relevant ones...
![Page 2: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/2.jpg)
222
Mike Duigou
Alan Bateman
Jim Laskey
Alex Buckley
Stuart Marks
Joe DarcyBruno Souza
Adam Bein
Adam Messinger
Mark Reinhold
Cameron Purdy
| Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
http::/javaspotlight.org@javaspotlight
![Page 3: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/3.jpg)
33
Binary Literals
• Binary literals
int mask = 0b101010101010;aShort = (short)0b1010000101000101;long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
HAPPY_FACE = { (short)0b0000011111100000; (short)0b0000100000010000; (short)0b0001000000001000; (short)0b0010000000000100; (short)0b0100000000000010; (short)0b1000011001100001; (short)0b1000011001100001; (short)0b1000000000000001; (short)0b1000000000000001; (short)0b1001000000001001; (short)0b1000100000010001; (short)0b0100011111100010; (short)0b0010000000000100; (short)0b0001000000001000; (short)0b0000100000010000; (short)0b0000011111100000; }
![Page 4: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/4.jpg)
44
Underscores in Numeric Literals
• Valid:
• Invalid:
int mask = 0b1010_1010_1010;long big = 9_223_783_036_967_937L;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_BFFE;
float pi1 = 3_.1415F; float pi2 = 3._1415F;long ssn = 999_99_9999_L;int x1 = _52; int x1 = 52_;int x2 = 0_x52; int x2 = 0x_52;
![Page 5: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/5.jpg)
55
Strings in Switch Statements
int monthNameToDays(String s, int year) { switch(s) { case "April": case "June": case "September": case "November": return 30;
case "January": case "March": case "May": case "July": case "August": case "December": return 31;
case "February”: ... default: ...
Did you know it produces generally more efficient byte codes than an if-then-else statement? Case Sensitive!
![Page 6: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/6.jpg)
66
Automatic Resource Management
try (InputStream in = new FileInputStream(src), OutputStream out = new FileOutputStream(dest)){ byte[] buf = new byte[8192]; int n; while (n = in.read(buf)) >= 0) out.write(buf, 0, n);}
• New superinterface java.lang.AutoCloseable• All AutoCloseable (throws Exception) and by extension
java.io.Closeable (throws IOException) types useable with try-with-resources
• Anything with a void close() method is a candidate• JDBC 4.1 retrofitted as AutoCloseable too
![Page 7: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/7.jpg)
77
Suppressed Exceptions
java.io.IOException
at Suppress.write(Suppress.java:19)
at Suppress.main(Suppress.java:8)
Suppressed: java.io.IOException
at Suppress.close(Suppress.java:24)
at Suppress.main(Suppress.java:9)
Suppressed: java.io.IOException
at Suppress.close(Suppress.java:24)
at Suppress.main(Suppress.java:9)
Throwable.getSupressed(); // Returns Throwable[]
Throwable.addSupressed(aThrowable);
![Page 8: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/8.jpg)
88
Multi-Catch
try {...
} catch (ClassCastException e) { doSomethingClever(e); throw e;} catch(InstantiationException |
NoSuchMethodException |InvocationTargetException e) {
// Useful if you do generic actions log(e);
throw e;}
![Page 9: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/9.jpg)
99
More Precise Rethrow
public void foo(String bar) throws FirstException, SecondException { try { // Code that may throw both
// FirstException and SecondException } catch (Exception e) { throw e; } }
• Prior to Java 7, this code would not compile, the types in throws would have to match the types in catch – foo would have to “throws Exception”• Java 7 adds support for this as long as try block calls all the exceptions in the throws clause, that the variable in the catch clause is the variable that is rethrown and the exceptions are not caught by another catch block.
![Page 10: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/10.jpg)
1010
Diamond Operator works many ways…
• With diamond (<>) compiler infers type
List<String> strList = new ArrayList<>();
OR
List<Map<String, List<String>> strList = new ArrayList<>();
OR
Foo<Bar> foo = new Foo<>();foo.mergeFoo(new Foo<>());
![Page 11: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/11.jpg)
1111
Varargs Warnings – Erasureclass Test { public static void main(String... args) { List<List<String>> monthsInTwoLanguages = Arrays.asList(Arrays.asList("January", "February"), Arrays.asList("Gennaio", "Febbraio" )); }} Test.java:7: warning:
[unchecked] unchecked generic array creation for varargs parameter of type List<String>[] Arrays.asList(Arrays.asList("January", ^1 warning
@SuppressWarnings(value = “unchecked”) // at call@SafeVarargs // at declaration
![Page 12: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/12.jpg)
1212
Why We Needed NIO2
• Methods didn’t throw exceptions when failing• Rename worked inconsistently • No symbolic link support• Additional support for meta data• Inefficient file meta data access• File methods didn’t scale• Walking a tree with symbolic links not possible
![Page 13: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/13.jpg)
1313
Java NIO.2 Features – Helper TypesFour key new helper Types new in Java 7• Class java.nio.file.Paths
• Exclusively static methods to return a Path by converting a string or Uniform Resource Identifier (URI)
• Interface java.nio.file.Path• Used for objects that represent the location of a file in a file
system, typically system dependent.
• Class java.nio.file.Files• Exclusively static methods to operate on files, directories and
other types of files
• Class java.nio.file.FileSystem
Typical use case:Use Paths to get a Path. Use Files to do stuff.
![Page 14: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/14.jpg)
1414
Java NIO.2 Example of Helpers in Action
• File copy is really easy– With fine grain control
• File move is supported– Optional atomic move supported
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);
Path src = Paths.get(“/home/fred/readme.txt”);Path dst = Paths.get(“/home/fred/readme.1st”);
Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
![Page 15: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/15.jpg)
1515
Java NIO.2 Features – Files Class
• Files helper class is feature rich:• Copy• Create Directories• Create Files• Create Links• Use of system “temp” directory• Delete• Attributes – Modified/Owner/Permissions/Size, etc.• Read/Write
![Page 16: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/16.jpg)
1616
Java NIO.2 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());
}
![Page 17: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/17.jpg)
1717
Java NIO.2 Symbolic Links• Path and Files are “link aware”• createSymbolicLink(Path, Path, FileAttribute<?>)
Path newLink = Paths.get(. . .);Path existingFile = Paths.get(. . .);try { Files.createSymnbolicLink(newLink, existingFile);} catch (IOException x) { System.err.println(x);} catch (UnsupportedOperationException x) { //Some file systems or some configurations
//may not support links System.err.println(x);}
![Page 18: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/18.jpg)
1818
Java NIO.2 More on Symbolic Links• Hard Links• Detect a Symbolic Link• Find the Target of the Link
try { Files.createLink(newLink, existingFile);} catch (IOException | UnsupportedOperationException x) { System.err.println(x);}
boolean isSymbolicLink = Files.isSymbolicLink(file);
Path link = ...;Files.readSymbolicLink(link));
![Page 19: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/19.jpg)
1919
Java NIO.2 Walking A File Tree• A FileVisitor interface makes walking a file tree for
search, or performing actions, trivial.• SimpleFileVisitor implements
preVisitDirectory(T dir, BasicFileAttributes attrs);visitFile(T dir, BasicFileAttributes attrs);visitFileFailed(T dir, IOException exc);postVisitDirectory(T dir, IOException exc);
SAMPLE:Path startingDir = ...;PrintFiles pf = new PrintFiles(); // SimpleFileVisitor sub
// visitFile(Path p, BasicFileAttributes bfa) {// System.out.println(file.getFileName());}
Files.walkFileTree(startingDir, pf);
![Page 20: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/20.jpg)
2020
Java NIO.2 Watching A Directory
• Create a WatchService “watcher” for the filesystem• Register a directory with the watcher• “Watcher” can be polled or waited on for events
• Events raised in the form of Keys• Retrieve the Key from the Watcher• Key has filename and events within it for create/delete/modify
• Ability to detect event overflows
![Page 21: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/21.jpg)
2121
NIO.2 Custom FileSystems
• FileSystems class is factory to great FileSystem (interface)
• Java 7 allows for developing custom FileSystems, for example:• Memory based or zip file based systems• Fault tolerant distributed file systems• Replacing or supplementing the default file system provider
• Two steps:• Implement java.nio.file.spi.FileSystemProvider
• URI, Caching, File Handling, etc.• Implement java.nio.file.FileSystem
• Roots, RW access, file store, etc.
![Page 22: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/22.jpg)
2222
NIO.2 filesystem provider for zip/jar archives
A fully-functional and supported NIO.2 filesystem provider for zip and jar files
Map<String, String> env = new HashMap<>();
env.put("create", "true");
// locate file system by using the syntax
// defined in java.net.JarURLConnection
URI u= URI.create("jar:file:/foo/zipfs/zipfstest.zip");
try (FileSystem z = FileSystems.newFileSystem(u, env)) {
Path externalTxtFile = Paths.get("/foo/zipfs/Sample.txt");
Path pathInZipfile = z.getPath("/Sample.txt");
// copy a file into the zip file
externalTxtFile.copyTo(pathInZipfile);
}
![Page 23: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/23.jpg)
2323
Mapping java.io.File to java.nio.file
• java.io.File
• File.canRead, canWrite, canExecute
• File.isDirectory(), File.isFile(), and File.length()
• File.lastModified() and File.setLastModified(long)
• File methods: setExecutable, setReadable, setReadOnly, setWritable
• new File(parent, "newfile")
• java.nio.file.Path
• Files.isReadable, Files.isWritable, and Files.isExecutable.
• Files.isDirectory(Path, LinkOption...), Files.isRegularFile(Path, LinkOption...), and Files.size(Path)
• Files.getLastModifiedTime(Path, LinkOption...) and Files.setLastMOdifiedTime(Path, FileTime)
• Files methods: setAttribute(Path, String, Object, LinkOption...).
• parent.resolve("newfile")
![Page 24: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/24.jpg)
2424
Mapping java.io.File to java.nio.fileContinued
• File.renameTo
• File.delete
• File.createNewFile
• File.deleteOnExit
• File.exists
• File.compareTo and equals
• File.getAbsolutePath and getAbsoluteFile
• File.getCanonicalPath and getCanonicalFile
• File.isHidden
• File.mkdir and mkdirs
• File.listRoots
• Files.move
• Files.delete
• Files.createFile
• DELETE_ON_CLOSE option in createFile
• Files.exists and Files.notExists
• Path.compareTo and equals
• Path.toAbsolutePath
• Path.toRealPath or normalize
• Files.isHidden
• Path.createDirectory
• FileSystem.getRootDirectories
![Page 25: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/25.jpg)
2525
More Information on NIO2
• OpenJDK: NIO project website on java.net. • Includes resources for
• Multicasting • Asynchronous I/O• Creating your own file system implementation
• File I/O Tutorial• Java Spotlight Podcast Episode 59
![Page 26: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/26.jpg)
2626
Concurrency APIs JSR 166y - Phasers
• Phaser• Barrier similar to CyclicBarrier and CountDownLatch• Used for many threads to wait at common barrier point
• For example, use this to create N threads that you want to do something simultaneously – “start gun” metaphore
• How is Phaser an improvement?• Dynamic add/remove “parties” to be sync’d• Better deadlock avoidance• Arrival “counting” and phase advance options, etc• Termination api’s • Tiering (tree structure)
• Rather than sync 100 threads, sync 2x50 then 2x.
![Page 27: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/27.jpg)
2727
Concurrency APIs JSR 166y - TransferQueue
• TransferQueue interface• Extension to BlockingQueue• Implemented by LinkedTransferQueue• Additional Benefits:
• Adds methods:• transfer(E e), tryTransfer(E e), tryTransfer(E e, long timeout), hadWaitingConsumer(), getWaitingConsumerCount()
• Allows for smarter queues to be built – sidestep the data structure if it’s known there are consumers waiting.
![Page 28: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/28.jpg)
2828
Fork Join Framework - JSR 166y - Pools
• ForkJoinPool– Service for running ForkJoinTasks– aFjp.execute(aTask); // async– aFjp.invoke(aTask); // wait– aFjp.submit(aTask); // async + future
– ForkJoinPool(); // default to platform– ForkJoinPool(int n); // # concurrent threads– ForJoinPool(n,aThreadFactory,exHandler,FIFOtasks); // Create your own thread handler, exception handler, and boolean on task ordering (default LIFO)
![Page 29: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/29.jpg)
2929
Fork Join Framework - JSR 166y - Tasks
• ForkJoinTask– The abstract base class for:• RecursiveAction
– A recursive resultless task– Implements compute() abstract
method to perform calculation• RecursiveTask
– Similar to RecursiveAction but returns a result
ForkJoinPool p = new ForkJoinPool(); MyTask mt = new MyTask(n); // implements compute p.submit(mt);while (!mt.isDone()) {/*THUMPER!*/ }System.out.println(mt.get());
![Page 30: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/30.jpg)
3030
Fork Join Framework - JSR 166y - compute()
• RecursiveAction example to increment an entire arrayprotected void compute() {
if (hi - lo < THRESHOLD) {
for (int i = lo; i < hi; ++i) array[i]++; } else {
int mid = (lo + hi) >>> 1;
invokeAll(new IncrementTask(array, lo, mid),
new IncrementTask(array, mid, hi));}
• RecursiveTask example for Fibonacci numbersprotected Integer compute() {
if (n <= 1) return n;
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
f1.fork(); f1.fork();
return f2.join() + f1.join();}
![Page 31: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/31.jpg)
3131
Concurrent Random Numbers - JSR 166y
• Existing RNG becomes unwitting source of contention between threads in concurrent apps
• Expected more needs of concurrent RNG with advent of Fork Join Framework
• Class java.util.ThreadLocalRandom• ThreadLocalRandom.current().nextDouble(…)• ThreadLocalRandom.current().nextInt (…)• ThreadLocalRandom.current().nextLong(…)
![Page 32: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/32.jpg)
3232
JSR 166y – ConcurrentLinkedDeque Class
• Unbound concurrent deque based on linked nodes• Like a Queue, but allows front and rear removal of elements
• Concurrent insert, remove and access on multiple threads
• Iterators are weakly consistent
![Page 33: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/33.jpg)
3333
ClassLoader Improvements – Deadlock Avoidance
Class Hierarchy:
class A extends B ; class C extends D ;
Custom Classloader CL1:
directly loads class A
delegates to custom ClassLoader CL2 for class B
Custom Classloader CL2:
directly loads class C
delegates to custom ClassLoader CL1 for class D
Thread 1:
Use CL1 to load class A (locks CL1)
defineClass A triggers loadClass B (try to lock CL2)
Thread 2:
Use CL2 to load class C (locks CL2)
defineClass C triggers loadClass D (try to lock CL1)
ClassLoaders were “not sufficiently granular”
and prone to deadlock
Java 7 has a “parallel capable classloader”
(in SE 7 – lock CL1+A)
(in SE7 – lock CL2+B)
(in SE 7 – lock CL2+C)
(in SE7 – lock CL1+D)
![Page 34: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/34.jpg)
3434
URLClassLoader Improvements – close()// create a class loader loading from "foo.jar"
URL url = new URL("file:foo.jar");
URLClassLoader loader = new URLClassLoader (new URL[] {url});
Class cl = Class.forName ("Foo", true, loader);
Runnable foo = (Runnable) cl.newInstance();
foo.run();
loader.close ();
// foo.jar gets updated somehow
loader = new URLClassLoader (new URL[] {url});
cl = Class.forName ("Foo", true, loader);
foo = (Runnable) cl.newInstance();
// run the new implementation of Foo
foo.run();
![Page 35: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/35.jpg)
3535
Unicode 4 -> Unicode 6.0• Unicode standard was originally 16 bit• 16 bits not sufficient for Unicode 6, but backward
compatibility needs to be maintained• Use String “U+hex” to express char in Unicode • Unicode 6.0 adds thousands of new characters• Support for properties and data files (mostly interesting
to Japanese Telcos and Indic scripts)• Full Unicode 6.0 REGEX support!
![Page 36: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/36.jpg)
3636
Extensible Currency Codes (ISO 4217)
• ISO 4217 Defines Currency Codes• Possible to supersede default currencies with <JAVA_HOME>/lib/currency.properties file
• Allows for supporting global changes without updating Java• Format: ISO 3166 Country code = ISO 4217 Codes
# Sample currency property if Canada adopts USD
# CA=CAD,124,2 is default ISO 4217 code
CA=USD,840,2
![Page 37: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/37.jpg)
3737
Number Shaper Enhancements • NumericShaper used to map numbers to non Latin char sets (since 1.4)
• NumericShaper traditionally used an int bitmask for defaults• Fine when there were only 19 defaults
• In Java 7 there are 34 (> 32 bits!!)
• Java 7 now has an Enum NumericShaper.Range
• Backward compatibility maintained, new API’s added for Enum use where desired
![Page 38: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/38.jpg)
3838
Locale enhancement – Categories
• Default Locale can be set independently for format resources (dates, numbers, currencies) and display resources (menus and dialogs)
• For example, an application for Japanese speakers who deal with US financial transactions may:
//Enum Locale.Category – DISPLAY and FORMAT//Default no arg get/set is DISPLAYLocale.setDefault(DISPLAY, Locale.JAPAN);Locale.setDefault(FORMAT, Locale.US);
![Page 39: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/39.jpg)
3939
Locale enhancement – BCP 47 Extensions
• Java 7 confirms to IETF BCP 47 (refs UTS #35)• Specify extensions to a Locale (get/set)• i.e., de-DE-co-phonebk• No guarantee the underlying platform can honour extension
Key Description Example Example Description
ca calendar algorithm ca-buddhist Thai Buddhist calendar
co collation type co-pinyin Pinyin ordering for Latin
k* collation parameters kf-upper Donald before donald
cu currency type cu-usd U.S. dollars
nu number type nu-jpanfin Japanese financial numerals
tz timezone tz-aldav Europe/Andorra
va common variant type va-posix POSIX style locale variant
![Page 40: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/40.jpg)
4040
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• Scalable Java 2D impl
![Page 41: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/41.jpg)
4141
JLayer ComponentEasy enrichment for Swing components
// wrap your component with JLayerJLayer<JPanel> layer = new JLayer<JPanel>(panel);// custom ui provides all extra functionalitylayer.setUI(myLayerUI);// add the layer as usual componentframe.add(layer);
![Page 42: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/42.jpg)
4242
Mixing of AWT and Swing – Works*
• As of 6u12 and 7u1, some caveats for scroll bars
![Page 43: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/43.jpg)
4343
Translucent Windows
• Private API added in 6u10, made public in Java 7• Support (based on platform) for:
• Uniform Translucency• Per Pixel Translucency• Per Pixel Transparency
// simple uniform:
aWindow.setOpacity(0.5f);
// Per pixel g2d is the g2d of a Jpanel on paintComponent(g)
Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B,0), 0.0f, getHeight(), new Color(R, G, B, 255), true);
g2d.setPaint(p);
g2d.fillRect(0, 0, getWidth(), getHeight());
![Page 44: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/44.jpg)
4444
Xrender-based Java 2D for modern X11
• Improved Graphics Performance• Off by default (backward compatibility)
• Quiet:
-Dsun.java2d.xrender=true
• Verbose (log on stdout if successful or not)
-Dsun.java2d.xrender=True
![Page 45: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/45.jpg)
4545
OpenType/CFF Fonts
• Java Platform must support TrueType fonts, other font technologies is implementation dependent
• Java 7 adds support for “Compact Font Format” - OpenType/CFF.
![Page 46: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/46.jpg)
4646
Better Support for Linux Fonts
• Five logical fonts since Java 1.0:• Serif, Sans-serif, Monospaced, Dialog, and
DialogInput• Must map to physical font on your system
• No consistency in fonts in Linux• Required editing fontconfig.properties• Java 7 on Linux (and Solaris 11) uses
system “libfontconfig”, reflecting what Gnome/KDE desktop applications use
![Page 47: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/47.jpg)
4747
HSV/HSL Tab on JColorChooser Class
![Page 48: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/48.jpg)
4848
JDBC 4.1
• Try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement
try (Statement stmt = con.createStatement()) { // ... }
• RowSet 1.1 introduces RowSetFactory and RowSetProvider
//Factory options (impl) set on cmd line or metainf
myRowSetFactory = RowSetProvider.newFactory();
jdbcRs = myRowSetFactory.createJdbcRowSet();
jdbcRs.setUrl("jdbc:myDriver:myAttribute"); //etc
jdbcRs.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
jdbcRs.execute();
![Page 49: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/49.jpg)
4949
Java DB Enhancements (Derby)
• JDK 7 includes Java DB 10.8.1.2• New Since JDK 6
• BOOLEAN data type• Table truncation• Query plan browsing
• Automatic calc of index stats• Unicode database names• Improved interrupt handling
• Can now interrupt connection threads• MAX optimization (faster!)• XML operator portability
![Page 50: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/50.jpg)
5050
Embedding JNLP File in Applet Tag
• Saves a network round trip first time applet is loaded• Base64 Encode the JNLP contents into a Javascript call:
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {} ;
<!-- Base64 encoded string trunc’d below for readability --> var parameters = {jnlp_href: 'dynamictree-applet.jnlp',
jnlp_embedded: 'PCEtLSAKLyoKICogQ29weX ... HA+Cg==' } ; deployJava.runApplet(attributes, parameters, '1.7');
</script>
![Page 51: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/51.jpg)
5151
<script>
function registerAppletStateHandler() {
switch (drawApplet.status) {
case 1: <!–- applet is loading -->
drawApplet.onLoad = onLoadHandler;
case 2: <!–- applet is loaded -->
case 3: <!–- error -->
document.getElementById("mydiv")
.innerHTML =“No need to onload";
}
}
Ability to detect applet init status on load
<!–- assume java.com/js/deployJava.js is loaded ->
var parameters = {java_status_events: 'true'};
<!–- set other params like jnlp->
deployJava.runApplet(attributes, parameters, '1.7');
...
</script>
function onLoadHandler(){
document.
getElementById("mydiv“)
.innerHTML =
"Applet has loaded";
draw();
}
![Page 52: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/52.jpg)
5252
Draggable Applet Decoration
• Applet decoration settings apply equally to in browser and out of browser launches – borderless, etc.
![Page 53: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/53.jpg)
5353
Other Misc New JNLP Stuff...
• Partially signed JNLP• Simplifies build and deployment in some scenarios• External JNLP file may differ from one embedded in jar
• Targeting resources to particular version of OS<resources os="Windows\ Vista Windows\ 7"> <jar href=“legacySound.jar"/> </resources>
• Better “install” preferences of an application• For example, attribute to determine if app appears on “Add
or Remove Programs panel”
![Page 54: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/54.jpg)
5454
VM: Updates to Experimental GC – G1
• Garbage First - “G1” intended to replace* Concurrent Mark-Sweep (CMS) in Hotspot at some future release
• G1 is included for experimentation in Java 7• Key benefits:
• More predictably “soft real-time” – temporal configuration• High throughput
• Basics:• Heap partitioned into equal-sized heap regions• Compacts as it proceeds – looks for regions with no live
objects for immediate reclamation
*not an official fwd looking statement
![Page 55: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/55.jpg)
5555
VM: Tiered Compilation
• Hotspot has 2 JIT’s “client” and “server”• Client starts fast, but let optimizations – best for clients• Server starts slower, but provides better optimizations
• Java 7 adds Tiered Compiliation• JIT the code first with “client”, and if it’s really hot code,
recompile with “server”• Has been around for a while, but not with a great
implementation
-server -XX:+TieredCompilation
Image from Rémi Forax showing the
DaCapo Jython benchmark.
http://www.java.net/blogs/forax
![Page 56: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/56.jpg)
5656
VM: Compressed OOPS by default
• Going from 32bit to 64bit system will grow the heap by ~1.5x simply because of bigger ordinary object pointers
• Memory is cheap, but bandwidth and cache is not• Compressed OOPS:
• Managed 32 bit pointers (similar heap sizes for 32/64 bit apps)• Scaled (8 x 4GB chunks) added to a 64 bit base
• Useful for heaps up to 32GB• Compressed OOPS will turn off when –Xmx > 32g
![Page 57: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/57.jpg)
5757
VM: invokedynamic Illustratedthis[method_name](x, y)
invokedynamic [#bootstrapMethod] .this_method_name
class LangaugeRuntime {bootstrapMethod(info) {
...return new CallSite();
}
class AClass {aMethod(x, y) {
...}
CallSite
MethodHandle
1. Invoke bootstrap
2. Produces CallSite
3.Complete linkage
4. Invokes method implementation
![Page 58: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/58.jpg)
5858
Java XML Technology Enhancements
• JAXP 1.4.5• Bug fixes and performance improvements
• JAX-WS 2.2.4• Bug fixes and performance improvements
• JAXB 2.2.3• Bug fixes and performance improvements
![Page 59: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/59.jpg)
5959
Elliptic Curve Cryptography (ECC)
• New Native Provider added to JDK 7• ECC-based algorithms (ECDSA/ECDH)• Enables ECC based Java Secure Sockets Extension
(JSSE)• Compared to traditional crypto systems like RSA,
ECC offers equivalent security:• With smaller key sizes• Faster computations• Lower power consumption• Memory and bandwidth savings
![Page 60: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/60.jpg)
6060
Transport Layer Security (TLS) Updates
• Support for TLS 1.1• Protection against cipher block chaining attacks
• Support for TLS 1.2• TLS Renegotiation• CertPath and TLS algorithm disabling
• Can deny specific algorithms in path processing and handshaking, i.e., MD2
![Page 61: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/61.jpg)
6161
JavaDoc Improvements in Java 7
• Section 508 accessibility guidelines• Captions, headings, etc.
• Previously, JavaDoc wrote to an OutputStream on the fly meaning it built the document sequentially, imposing limitations
• Now uses internal “HTMLTree” classes• Generates compliant HTML• Allows for more advancements in the future
• Removes limitation of only being able to execute only once in any VM• Was fine when used as a command line tool• Continuous build, etc, made it necessary to address this!
![Page 62: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/62.jpg)
6262
CSS for JavaDoc - stylesheet.css
![Page 63: 55 New Features in Java 7](https://reader033.vdocument.in/reader033/viewer/2022061207/5487b5b7b47959e20c8b5597/html5/thumbnails/63.jpg)
6363
The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions.The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.