Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Anuncio
Próximo SlideShare
Java 5 and 6 New Features
Java 5 and 6 New Features
Cargando en…3
×

Eche un vistazo a continuación

1 de 63 Anuncio

55 New Features in Java 7

Descargar para leer sin conexión

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

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

Anuncio
Anuncio

Más Contenido Relacionado

Presentaciones para usted (20)

Similares a 55 New Features in Java 7 (20)

Anuncio

Más reciente (20)

Anuncio

55 New Features in Java 7

  1. 1. 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... 1 1
  2. 2. Joe Darcy Bruno Souza Stuart Marks Adam Bein Alex Buckley Adam Messinger Jim Laskey Mark Reinhold Alan Bateman Cameron Purdy http::/javaspotlight.org Mike Duigou @javaspotlight 2 2 | Copyright © 2011, Oracle and/or its affiliates. All rights 2 reserved.
  3. 3. 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; } 3 3
  4. 4. Underscores in Numeric Literals • Valid: 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; • Invalid: 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; 4 4
  5. 5. 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”: Did you know it produces ... generally more efficient byte default: ... codes than an if-then-else statement? Case Sensitive! 5 5
  6. 6. 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 6 6
  7. 7. 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); 7 7
  8. 8. 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; } 8 8
  9. 9. 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. 9 9
  10. 10. 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<>()); 10 10
  11. 11. Varargs Warnings – Erasure class 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 11 11
  12. 12. 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 12 12
  13. 13. Java NIO.2 Features – Helper Types Four 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. 13 13
  14. 14. Java NIO.2 Example of Helpers in Action • File copy is really easy – With fine grain control Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/copy_readme.txt”); Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); • File move is supported – Optional atomic move supported Path src = Paths.get(“/home/fred/readme.txt”); Path dst = Paths.get(“/home/fred/readme.1st”); Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE); 14 14
  15. 15. 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 15 15
  16. 16. 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()); } 16 16
  17. 17. 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); } 17 17
  18. 18. 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)); 18 18
  19. 19. 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); 19 19
  20. 20. 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 20 20
  21. 21. 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. 21 21
  22. 22. 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); } 22 22
  23. 23. Mapping java.io.File to java.nio.file • java.io.File • java.nio.file.Path • File.canRead, canWrite, • Files.isReadable, Files.isWritable, and canExecute Files.isExecutable. • File.isDirectory(), File.isFile(), • Files.isDirectory(Path, LinkOption...), and File.length() Files.isRegularFile(Path, LinkOption...), and Files.size(Path) • File.lastModified() and • Files.getLastModifiedTime(Path, File.setLastModified(long) LinkOption...) and Files.setLastMOdifiedTime(Path, FileTime) • File methods: setExecutable, setReadable, setReadOnly, • Files methods: setAttribute(Path, String, setWritable Object, LinkOption...). • new File(parent, "newfile") • parent.resolve("newfile") 23 23
  24. 24. Mapping java.io.File to java.nio.file Continued • File.renameTo • Files.move • File.delete • Files.delete • File.createNewFile • Files.createFile • File.deleteOnExit • DELETE_ON_CLOSE option in createFile • File.exists • Files.exists and Files.notExists • File.compareTo and equals • Path.compareTo and equals • File.getAbsolutePath and • Path.toAbsolutePath getAbsoluteFile • File.getCanonicalPath and • Path.toRealPath or normalize getCanonicalFile • File.isHidden • Files.isHidden • File.mkdir and mkdirs • Path.createDirectory • File.listRoots • FileSystem.getRootDirectories 24 24
  25. 25. 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 25 25
  26. 26. Concurrency APIs JSR 166y - Phasers haser • 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. 26 26
  27. 27. Concurrency APIs JSR 166y - TransferQueue ransferQueue 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. 27 27
  28. 28. 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) 28 28
  29. 29. 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()); 29 29
  30. 30. Fork Join Framework - JSR 166y - compute() • RecursiveAction example to increment an entire array protected 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 numbers protected 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();} 30 30
  31. 31. 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(…) 31 31
  32. 32. 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 32 32
  33. 33. ClassLoader Improvements – Deadlock Avoidance Class Hierarchy: ClassLoaders were “not class A extends B ; class C extends D ; sufficiently granular” and prone to Custom Classloader CL1: deadlock directly loads class A delegates to custom ClassLoader CL2 for class B Java 7 has a “parallel Custom Classloader CL2: capable classloader” directly loads class C delegates to custom ClassLoader CL1 for class D Thread 1: Use CL1 to load class A (locks CL1) (in SE 7 – lock CL1+A) defineClass A triggers loadClass B (try to lock CL2) (in SE7 – lock CL2+B) Thread 2: Use CL2 to load class C (locks CL2) (in SE 7 – lock CL2+C) defineClass C triggers loadClass D (try to lock CL1) (in SE7 – lock CL1+D) 33 33
  34. 34. 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(); 34 34
  35. 35. 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! 35 35
  36. 36. 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 36 36
  37. 37. 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 37 37
  38. 38. 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 DISPLAY Locale.setDefault(DISPLAY, Locale.JAPAN); Locale.setDefault(FORMAT, Locale.US); 38 38
  39. 39. 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 39 39
  40. 40. 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 40 40
  41. 41. JLayer Component Easy enrichment for Swing components // wrap your component with JLayer JLayer<JPanel> layer = new JLayer<JPanel>(panel); // custom ui provides all extra functionality layer.setUI(myLayerUI); // add the layer as usual component frame.add(layer); 41 41
  42. 42. Mixing of AWT and Swing – Works* • As of 6u12 and 7u1, some caveats for scroll bars 42 42
  43. 43. 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()); 43 43
  44. 44. 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 44 44
  45. 45. 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. 45 45
  46. 46. 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 46 46
  47. 47. HSV/HSL Tab on JColorChooser Class 47 47
  48. 48. 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(); 48 48
  49. 49. 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 49 49
  50. 50. 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> 50 50
  51. 51. Ability to detect applet init status on load <script> function onLoadHandler(){ function registerAppletStateHandler() { document. switch (drawApplet.status) { getElementById("mydiv“) case 1: <!–- applet is loading --> .innerHTML = drawApplet.onLoad = onLoadHandler; "Applet has loaded"; case 2: <!–- applet is loaded --> draw(); case 3: <!–- error --> } document.getElementById("mydiv") .innerHTML =“No need to onload"; } <!–- 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> 51 51
  52. 52. Draggable Applet Decoration • Applet decoration settings apply equally to in browser and out of browser launches – borderless, etc. 52 52
  53. 53. 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” 53 53
  54. 54. 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 54 54
  55. 55. 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 55 55
  56. 56. 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 56 56
  57. 57. VM: invokedynamic Illustrated this[method_name](x, y) invokedynamic [#bootstrapMethod] .this_method_name 1. Invoke bootstrap class LangaugeRuntime { 2. Produces bootstrapMethod(info) { CallSite ... 3.Complete linkage return new CallSite(); } CallSite class AClass { aMethod(x, y) { 4. Invokes method Method ... implementation Handle } 57 57
  58. 58. 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 58 58
  59. 59. 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 59 59
  60. 60. 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 60 60
  61. 61. 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! 61 61
  62. 62. CSS for JavaDoc - stylesheet.css 62 62
  63. 63. 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. 63 63

Notas del editor

  • This slide show the contents for Java SE 7, and we will go through each of this topics on a separate section, so here is just the list. JSR-336 is called an umbrella JSR and provides the complete set of features that are included in Java SE 7, even though several components have their own JSR 6/27/11
  • The Java Spotlight Podcast is a weekly podcast featuring a number internal and external developers in each episodes weekly feature interview. It also includes segments on the news of the week as well as upcoming events and a what ’ s cool segment. You can follow the spotlight on twitter, Itunes or go directly to the web page at http://javaspotlight.org
  • 6/27/11 Finally we have support for binary literals.
  • 6/27/11 Support for underscores, that allow you to group together, and make it easier to read the literals.
  • 6/27/11 This show the monthNameToDays method using the JDK 7, where you can use the string in the switch statement, making your code, smaller, clearer, and easier to read.
  • 6/27/11 JDK 7 introduce a solution for the issues presented in the previous slides, the automatic resource management. Now you don&apos;t have to worry about closing your resources, they will be automatically closed whe the try block finish execution. Please note the new definition of the try block, where you include the resources to be managed.
  • With automatic resource management even though there are potentially several levels of nesting for the finally clauses that are not immediately visible the full trace of the exceptions that were thrown will be reported. 6/27/11
  • 6/27/11 Now with JDK 7 you can group under the same catch, several exceptions using the “|&apos; operand. Simpler, cleaner and you can reuse common code.
  • 6/27/11 JDK 7 introduce the diamond operator, now you only need to specify once the type of elements been hold by the collection, on the left hand side, the rest is taking care for you, as java will “infer” the type that will go on the right hand side. This is more complex than just having the compiler perform string substitution. For certain cases the type to be inserted is not represented by the string in the variable declaration (wildcards are a good example). The compiler must infer the type parameter for the instantiation from the type parameter of the variable declaration. List&lt;? extends A&gt; la; la = new ArrayList&lt;B&gt;(); la = new ArrayList&lt;C&gt;(); la = new ArrayList&lt;D&gt;(); List&lt;? super B&gt; lb; lb = new ArrayList&lt;A&gt;(); //fine lb = new ArrayList&lt;C&gt;(); //will not compile public void someMethod(List&lt;? extends B&gt; lb) {     B b = lb.get(0); // is fine     lb.add(new C()); //will not compile as we do not know the type of the list, only that it is bounded above by B } public void otherMethod(List&lt;? super B&gt; lb) {     B b = lb.get(0); // will not compile as we do not know whether the list is of type B, it may be a List&lt;A&gt; and only contain instances of A     lb.add(new B()); // is fine, as we know that it will be a super type of A }
  • Lets study this code closely as we get an unchecked generic array warning. There is a heavy use of the static method asList from the Arrays class, defined as: public static &lt;T&gt; List&lt;T&gt; asList(T... a) Returns a fixed-size list backed by the specified array. Lets go back to the code. We are defining monthsInTwoLanguages, and we are expecting it to be a List&lt;List&lt;String&gt;&gt;. First we call Arrays.asList(&amp;quot;January&amp;quot;, &amp;quot;February&amp;quot;), this will return a List&lt;Strings&gt;, in other words a list with the months in English. Then we call Arrays.asList(&amp;quot;Gennaio&amp;quot;, &amp;quot;Febbraio&amp;quot; )); and again we will get a List&lt;Strings&gt;, in this case it will be a list with the months in Italian. Then we call Arrays.asList(Arrays.asList(&amp;quot;January&amp;quot;, &amp;quot;February&amp;quot;), Arrays.asList(&amp;quot;Gennaio&amp;quot;, &amp;quot;Febbraio&amp;quot; )); in this case the call seems to be Arrays.asList( List&lt;String&gt;, List&lt;String&gt;) , from previous paragraph. Then we expect to get as result a List&lt;List &lt;String&gt;&gt; that is the expected type for our definition, so why are we getting this warning? When a generic type is instantiated in java, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. This is done to maintain binary compatibility with Java libraries and applications that were created before generics. Then when we do the first asList call, the only stored information is List, we don&apos;t store any information about String, the type of elements hold by this list. And it&apos;s the same scenario for the second asList call. When we finally get to the 3 rd asList call, know we are returning a new List &lt;List &lt;???&gt;&gt; but we didn&apos;t store any information about String, so the compiler doesn&apos;t know what ??? means, In our case we are sure that we have String types, but because we don&apos;t have any information about it, it could be wrong, the compiler doesn&apos;t have this information, and that&apos;s the reason why we get the warning. There could be a potential issue. 6/27/11
  • Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks. 1. Many methods didn&apos;t throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a &amp;quot;delete fail&amp;quot; but wouldn&apos;t know if it was because the file didn&apos;t exist, the user didn&apos;t have permissions, or there was some other problem. 2. The rename method didn&apos;t work consistently across platforms. 3. There was no real support for symbolic links. 4. More support for metadata was desired, such as file permissions, file owner, and other security attributes. 5. Accessing file metadata was inefficient. 6. Many of the File methods didn&apos;t scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service. 7. It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links. 6/27/11
  • 6/27/11 From a developer’s perspective the biggest change will be to replace use of the File object with the Path object. Since File was not designed to be extended it was not possible to add functionality so a new class was required. In many places this can be used in exactly the same way, but there are a few differences that developers will need to be aware of to use this correctly.   The java.nio.file package provides extensive support for file and file system I/O. This is a very comprehensive API, but the key entry points are as follows:   The Files class is the other primary entrypoint of the java.nio.file package. This class offers a rich set of static methods for reading, writing, and manipulating files and directories.   The Paths interface consists exclusively of static methods that return a Path by converting a path string or URI .   The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. Path methods are sometimes called syntactic operations, because they operate on the path itself and don&apos;t access the file system.   The FileSystem class has a variety of methods for obtaining information about the file system.  
  • Finally the most obvious file system operations are supported in a clean consistent way in Java. Copying, moving and renaming files is all performed using a Path for each part of the operation. Three copy options can also be specified to copy the attributes of the file rather than using the defaults, to replace an existing file if one already exists at the destination path and to make the move an atomic operation from the filesystem perspective. The Files class provides a large number of utility methods for typical filesystem operations (copy, move, delete, createDirectory and so on).
  • 6/27/11
  • The DirectoryStream class provides an iterator that can be used to read entries from a directory. One point of note is that, as the DirectoryStream provides an Iterator, it is not possible to use the DirectoryStream more than once, since there is no way to reset an Iterator,. There is built in support for regular expressions so complex patterns can be used like *.{c,h,cpp,hpp,java}
  • The java.nio.file package, and the Path class in particular, is &amp;quot;link aware.&amp;quot; Every Path method either detects what to do when a symbolic link is encountered, or it provides an option enabling you to configure the behavior when a symbolic link is encountered.   The example code snippet creates a symbolic link with default permissions.   The FileAttributes vararg enables you to specify initial file attributes that are set atomically when the link is created. However, this argument is intended for future use and is not currently implemented.
  • You can create a hard (or regular ) link to an existing file by using the createLink(Path, Path) method. The second Path argument locates the existing file, and it must exist or a NoSuchFileException is thrown. To determine whether a Path instance is a symbolic link, you can use the isSymbolicLink(Path) method. You can obtain the target of a symbolic link by using the readSymbolicLink(Path) method. If the Path is not a symbolic link, this method throws a NotLinkException.
  • To walk a file tree, you first need to implement a FileVisitor. A FileVisitor specifies the required behavior at key points in the traversal process: when a file is visited, before a directory is accessed, after a directory is accessed, or when a failure occurs. The interface has five methods that correspond to these situations:   preVisitDirectory – Invoked before a directory&apos;s entries are visited. postVisitDirectory – Invoked after all the entries in a directory are visited. If any errors are encountered, the specific exception is passed to the method. visitFile – Invoked on the file being visited. The file&apos;s BasicFileAttributes is passed to the method, or you can use the file attributes package to read a specific set of attributes. For example, you can choose to read the file&apos;s DosFileAttributeView to determine if the file has the &amp;quot;hidden&amp;quot; bit set. visitFileFailed – Invoked when the file cannot be accessed. The specific exception is passed to the method. You can choose whether to throw the exception, print it to the console or a log file, and so on.   If you don&apos;t need to implement all five of the FileVisitor methods, instead of implementing the FileVisitor interface, you can extend the SimpleFileVisitor class. This class, which implements the FileVisitor interface, visits all files in a tree and throws an IOError when an error is encountered. You can extend this class and override only the methods that you require.   Caveats:   A file tree is walked depth first, but you cannot make any assumptions about the iteration order that subdirectories are visited.   If your program will be changing the file system, you need to carefully consider how you implement your FileVisitor.   You need to decide whether you want symbolic links to be followed. If you are deleting files, for example, following symbolic links might not be advisable. If you are copying a file tree, you might want to allow it. By default, walkFileTree does not follow symbolic links.
  • The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.
  • To provide extensibility the Filesystem class provides an interface to a Filesystem which can be any form of file storage system, for example a ZIP file can be accessed as if it were a filesystem even though it is itself a file on another filesystem. The attribute package provides enhanced access to metadata for files and also solves a longstanding performance problem, namely that every request for an attribute results in a separate stat() call 6/27/11
  • 6/27/11
  • There is no one-to-one correspondence between the two APIs, but the following table on the next two slides gives a general idea of what functionality in the java.io.File API maps to in the java.nio.file API 6/27/11
  • There is no one-to-one correspondence between the two APIs, but the following table on the next two slides gives a general idea of what functionality in the java.io.File API maps to in the java.nio.file API 6/27/11
  • More information on NIO2 6/27/11
  • 6/27/11 Java SE 7 includes updates to the concurrency APIs first introduced in Java SE 5. This is an update to an update;the orinial utilities were defined in JSR166. This was eXtended in JSR166x (Java SE 6) and extended further through JSR166y (Java SE 7). Introduces the fork-join framework for fine grained parallelism The Phaser which is a reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage. A TransferQueue is a BlockingQueue in which producers may wait for consumers to receive elements. A TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll, while at other times enqueue elements (via method put) without waiting for receipt. Non-blocking and time-out versions of tryTransfer are also available. A TransferQueue may also be queried, via hasWaitingConsumer(), whether there are any threads waiting for items, which is a converse analogy to a peek operation. Like other blocking queues, a TransferQueue may be capacity bounded. If so, an attempted transfer operation may initially block waiting for available space, and/or subsequently block waiting for reception by a consumer. Note that in a queue with zero capacity, such as SynchronousQueue, put and transfer are effectively synonymous. This is implemented by the LinkedTransferQuue which is an unbounded TransferQueue based on linked nodes. This queue orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.
  • 6/27/11 Java SE 7 includes updates to the concurrency APIs first introduced in Java SE 5. This is an update to an update;the orinial utilities were defined in JSR166. This was eXtended in JSR166x (Java SE 6) and extended further through JSR166y (Java SE 7). Introduces the fork-join framework for fine grained parallelism The Phaser which is a reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage. A TransferQueue is a BlockingQueue in which producers may wait for consumers to receive elements. A TransferQueue may be useful for example in message passing applications in which producers sometimes (using method transfer(E)) await receipt of elements by consumers invoking take or poll, while at other times enqueue elements (via method put) without waiting for receipt. Non-blocking and time-out versions of tryTransfer are also available. A TransferQueue may also be queried, via hasWaitingConsumer(), whether there are any threads waiting for items, which is a converse analogy to a peek operation. Like other blocking queues, a TransferQueue may be capacity bounded. If so, an attempted transfer operation may initially block waiting for available space, and/or subsequently block waiting for reception by a consumer. Note that in a queue with zero capacity, such as SynchronousQueue, put and transfer are effectively synonymous. This is implemented by the LinkedTransferQuue which is an unbounded TransferQueue based on linked nodes. This queue orders elements FIFO (first-in-first-out) with respect to any given producer. The head of the queue is that element that has been on the queue the longest time for some producer. The tail of the queue is that element that has been on the queue the shortest time for some producer.
  • The main classes for the Fork Join framework: ForkJoinPool – Creates a pool of worker threads to execute the tasks. ForkJoinTask – a task to be processed RecursiveAction – A recursively decomposable task that does not return a result RecursiveTask – A recursively decomposable task that does return a value
  • The main classes for the Fork Join framework: ForkJoinPool – Creates a pool of worker threads to execute the tasks. ForkJoinTask – a task to be processed RecursiveAction – A recursively decomposable task that does not return a result RecursiveTask – A recursively decomposable task that does return a value
  • The main classes for the Fork Join framework: ForkJoinPool – Creates a pool of worker threads to execute the tasks. ForkJoinTask – a task to be processed RecursiveAction – A recursively decomposable task that does not return a result RecursiveTask – A recursively decomposable task that does return a value
  • 6/27/11
  • 6/27/11 The Nimbus look and feel was introduced in Java SE 6 update 10 as a replacement for the metal cross platform L&amp;F. In Java SE 7 this has been moved to a standard part of the platform (previously it was an oracle extension package, now it is in the javax.swing.plaf package). The decision was made not to make this the default L&amp;F, this will continue to be Metal. Although many people in the community wanted this it was decided that the impact on existing applications would be too great.
  • 6/27/11 The Jlayer component provides an easy way to add an overlay to existing Swing components. Examples are a progress wheel or highlighting only vallid choices in a multiple-choice component.
  • To help understand this we provide a diagram. To shorten this presentation you may want to remove the details of how invokedynamic works as this does not impact on most developers.
  • 6/27/11 Here are a few miscellaneous things that don’t fit into the preceeding areas. Some minor changes to cryptography in terms of the underlying algorithm used. Various updates to Java APIs defined in other JSRs Some minor changes to class loading which will only have an impact on a very small number of developers. Finally! Javadocs get CSS support so we can bring javadocs into the 21 st Century.
  • 6/27/11 This is the standard Oracle safe-harbour statement. Please allow the audience to read this in their own time.

×