SlideShare a Scribd company logo
Java 7 new features
Java User Group Latvia
www.jug.lv
Java 7
Project began in August 2006
JDK7 is done via Open JDK effort
Major release – JVM, language and library changes
Current status – milestone M10, build b115, planned
release Mid 2011
Initially planned features
Closures – Project Lambda
Small language changes – Project Coin
Modularity for Java platform – Project Jigsaw
Support for dynamically-typed languages
Core and IO library extensions
Swing and UI related changes
Support for updated standards - Unicode, localization,
security, cryptography, XML and JDBC
Two release plans
Plan A
All features, release in Mid 2012
Plan B
JDK 7 minus Lambda, Jigsaw and part of Coin,
release in Mid 2011
JDK 8, release in late 2012
Plan B selected
Plan A
All features, release in Mid 2012
Plan B
JDK 7 minus Lambda, Jigsaw and part of Coin,
release in Mid 2011
JDK 8, release in late 2012
Approved feature list
JSR 292: Support for Dynamically-Typed Languages
(“InvokeDynamic”)
Small Language Enhancements (Project Coin)
Concurrency and Collections Updates (including the Fork/Join
Framework)
Upgrade Class-Loader Architecture
Unicode 6.0
JSR 203: More New I/O APIs (“NIO 2”)
Updated cryptography
JDBC 4.1
Translucent & Shaped Windows
Heavyweight/Lightweight Component Mixing
Swing: Nimbus Look-and-Feel, JLayer Component
Update the XML Stack (JAXP, JAXB, & JAX-WS)
Language enhancements - Project Coin
Strings in switch statement
GregorianCalendar c = new GregorianCalendar();
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":
return 28 + (c.isLeapYear(year) ? 1 : 0);
default:
return -1;
}
}
Improved Type Inference for Generic
Instance Creation
Map<Integer, List<String>> map =
new HashMap<Integer, List<String>>();
New “diamond” operator:
Map<Integer, List<String>> map = new HashMap<>();
List<?> l = new ArrayList<>();
Try-with-resources
void copy(String src, String dest) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dest);
try {
byte[] buf = new byte[8 * 1024];
int n;
while ((n = in.read(buf)) >= 0)
out.write(buf, 0, n);
} finally {
out.close();
}
} finally {
in.close();
}
}
Try-with-resources
void copy(String src, String dest) throws IOException {
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);
}
}
Try-with-resources
void copy(String src, String dest) {
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);
} catch (IOException e) {
e.printStackTrace();
}
}
Try-with-resources
package java.lang;
public interface AutoCloseable {
void close() throws Exception;
}
package java.io;
public interface Closeable extends AutoCloseable {
void close() throws IOException;
}
Multi-catch
try {
String.class.newInstance();
} catch (final IllegalAccessException |
InstantiationException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
// handle exception
}
Integer and binary literals
byte b = 0b00100101;
int phoneNumber = 123_456_7890;
long creditCardNumber = 1234_5678_9012_3456L;
int hexBytes = 0xFF_EC_DE_5E;
Simplified Varargs Method Invocation
List<String> a = new ArrayList<String>(),
b = new ArrayList<String>(),
c = new ArrayList<String>();
// Warning: [unchecked] unchecked generic array
// creation for varargs parameter of type
// List<String>[]
return Arrays.asList(a, b, c);
Language enhancements postponed
until Java 8
Language enhancements in Java 8
Collection literals and indexing
List<String> cities = ["Riga", "London", "Tokio"];
Set<String> countries = { "LV", "LT", "EE" };
Map<String, Double> atomicWeights = { "H" : 1.0079,
"He" : 4.0026, "Li" : 6.941 };
String city = cities[0];
Double weight = atomicWeights["H"];
Language enhancements in Java 8
Closures
#{ int x -> x + 1 }
#{ System.out.println("Hello, World!") }
list.forEach(#{ e -> System.out.println(e) });
Arrays.sort(array, #{ a, b -> a.compareToIgnoreCase(b) });
Language enhancements in Java 8
Method references
class Person {
public static int compareByAge(Person a, Person b) { ... }
}
Person[] people = ...
Arrays.sort(people, #Person.compareByAge);
Arrays.sort(people, #Person.compareByAge(Person, Person));
Arrays.sort(people, #comparatorHolder.comparePersonByAge);
JSR 292 – Support for Dynamically-
Typed languages
JSR 292 - Overview
Dynamic languages on the JVM
JSR 223 implemented in JDK6
JVM initially designed for statically-typed language
4 bytecode instructions available for method invocations
Invokestatic
Invokevirtual
Invokespecial
Invokeinterface
new bytecode instruction "invokedynamic“ and Method
Handles
java.dyn package
JSR 292 – Method Handles
Method handle is a lightweight pointer or reference to a
method
java.dyn.MethodHandle
Example
public void testMethodHandle() throws Throwable {
MethodHandle hndl = MethodHandles.lookup().findVirtual(
PrintStream.class, "println",
MethodType.methodType(void.class, String.class));
hndl.<void>invokeGeneric(System.out, "Hello, MethodHandle!");
}
JSR 292 Invokedynamic – how it works?
JVM encounters invokedynamic instruction
JVM invokes the bootstrap method
The Bootstrap method resolves the method handle
The Bootstrap method must be previously registered in
JVM
Future calls don't require the Bootstrap method
invocation
JSR 292 InvokeDynamic, Java example
public void testDynamic() throws Throwable {
InvokeDynamic.<void>greet("World");
}
static {
Linkage.registerBootstrapMethod("bootstrap");
}
public static void greet(String str) {
System.out.println("Hello, dynamic " + str);
}
private static CallSite bootstrap(Class caller, String name,
MethodType type) {
CallSite site = new CallSite(caller, name, MethodType.make(void.class));
site.setTarget(MethodHandles.lookup().findStatic(Test.class, name,
MethodType.make(void.class, String.class)));
return site;
}
NIO.2
NIO.2 – Paths
java.nio.file.Path – a replacement for java.io.File
File file = new File("index.html");
Path path = Paths.get("index.html");
Path path = new File("index.html").toPath();
All Path methods throw exceptions in case of errors
if (!file.delete()){
...
}
try {
path.delete();
} catch (IOException e) {
...
}
NIO.2 – FileSystem
Provides interface to file system
Default file system is local/platform file system
FileSystem local = FileSystems.getDefault();
Path p = local.getPath(“filename");
Path p2 = Paths.get(“filename”);
Jar and Zip file systems included
NIO.2 – DirectoryStream
DirectoryStream to iterate over the entries
Scales to large directories
Filter using glob, regex, or custom filter
try (DirectoryStream<Path> stream =
dir.newDirectoryStream("*.{c,h,cpp,hpp,java}")) {
for (Path entry : stream) {
...
}
}
NIO.2 - Files.walkFileTree
Walks a file tree rooted at a given starting file
Invoke FileVisitor method for each file/directory
interface FileVisitor<T> {
FileVisitResult preVisitDirectory(T dir);
FileVisitResult visitFile(T file, BasicFileAttributes attrs);
FileVisitResult visitFileFailed(T file, IOException exc);
FileVisitResult postVisitDirectory(T dir, IOException exc);
}
SimpleFileVisitor – a default implementation
NIO.2 - File change notifications
Current approach – polling the file system
WatchService – watch registered objects (Watchables) for changes
WatchService watcher =
path.getFileSystem().newWatchService();
path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY);
for (;;) {
WatchKey watchKey = watcher.take();
for (WatchEvent event : watchKey.pollEvents()) {
System.out.println(event.kind() + " : “
+ event.context());
}
watchKey.reset();
}
Fork/Join framework
Fork/Join Framework
Multicore era approaching
Moore’s Law doesn’t work since ~2003
Current solution (java.util.concurrent) has its
limitations
Coarse grained parallelism
Inefficient CPU utilization
Solution: Fork/Join framework
Fork/Join – Divide and conquer
Result solve(Problem problem) {
if (problem.size < SEQUENTIAL_THRESHOLD)
return solveSequentially(problem);
else {
Result left, right;
INVOKE-IN-PARALLEL {
left = solve(extractLeftHalf(problem));
right = solve(extractRightHalf(problem));
}
return combine(left, right);
}
}
Fork/Join - architecture
ForkJoinExecutor, ForkJoinTask
Each worker thread has it’s own task queue (deque) –
no concurrency between treads for tasks
Work stealing algorithm – threads are never idle
Fork/Join - ParallelArray
ParallelArray<T>, ParallelLongArray etc.
Supports filtering, mapping, searching, sorting,
reducing etc.
ParallelArray example
ParallelArray<Order> orders = new ParallelArray<>(fjPool, data);
double maxAmount = orders
.withFilter(madeThisYear)
.withMapping(getAmount)
.max();
static final Ops.Predicate<Order> madeThisYear = new Ops.Predicate<>() {
public boolean op(Order o) {
return o.getYear() == thisYear;
}
};
static final Ops.ObjectToDouble<Order> getAmount = new
Ops.ObjectToDouble<>() {
public double op(Order o) {
return o.getAmount();
}
};
Try it yourself
Download JDK 7 early access
https://jdk7.dev.java.net/
Questions

More Related Content

PDF
Java7 New Features and Code Examples
PPTX
Hadoop
PDF
Java 7 New Features
ODP
Biopython
KEY
R for Pirates. ESCCONF October 27, 2011
PDF
服务框架: Thrift & PasteScript
PPTX
PPT
Java 7 - short intro to NIO.2
Java7 New Features and Code Examples
Hadoop
Java 7 New Features
Biopython
R for Pirates. ESCCONF October 27, 2011
服务框架: Thrift & PasteScript
Java 7 - short intro to NIO.2

What's hot (20)

PDF
Looking Ahead to Tcl 8.6
PDF
JAVA NIO
PDF
An introduction into Spring Data
PDF
Files and streams
PDF
ROracle
PDF
10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code
PDF
BP107: Ten Lines Or Less: Interesting Things You Can Do In Java With Minimal ...
PPTX
Python mongo db-training-europython-2011
PPT
Spring data presentation
PPTX
Session 23 - JDBC
PPTX
Adventures in TclOO
PPTX
Session 22 - Java IO, Serialization
DOCX
Advance Java Programs skeleton
PDF
System Programming and Administration
PDF
Data access 2.0? Please welcome: Spring Data!
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
PPTX
Session 24 - JDBC, Intro to Enterprise Java
PPTX
EuroPython 2015 - Big Data with Python and Hadoop
PPT
JDBC
Looking Ahead to Tcl 8.6
JAVA NIO
An introduction into Spring Data
Files and streams
ROracle
10 Lines or Less; Interesting Things You Can Do In Java With Minimal Code
BP107: Ten Lines Or Less: Interesting Things You Can Do In Java With Minimal ...
Python mongo db-training-europython-2011
Spring data presentation
Session 23 - JDBC
Adventures in TclOO
Session 22 - Java IO, Serialization
Advance Java Programs skeleton
System Programming and Administration
Data access 2.0? Please welcome: Spring Data!
Lambda Chops - Recipes for Simpler, More Expressive Code
Session 24 - JDBC, Intro to Enterprise Java
EuroPython 2015 - Big Data with Python and Hadoop
JDBC
Ad

Similar to Jug java7 (20)

PPT
JDK1.7 features
PPTX
Java 7, 8 & 9 - Moving the language forward
PPTX
Scalable and Flexible Machine Learning With Scala @ LinkedIn
PDF
WhatsNewNIO2.pdf
PPTX
Java 7 & 8 New Features
PPTX
Java 7 Whats New(), Whats Next() from Oredev
PDF
5. Ввод-вывод, доступ к файловой системе
PDF
New Features Of JDK 7
PDF
JRubyKaigi2010 Hadoop Papyrus
PDF
Java I/o streams
PPTX
PDF
Power tools in Java
PDF
Why is Java relevant? New features of Java8
PPTX
Golang basics for Java developers - Part 1
PPTX
Twitter Author Prediction from Tweets using Bayesian Network
ODP
Java 7 Features and Enhancements
PDF
Scala is java8.next()
PDF
Terence Barr - jdk7+8 - 24mai2011
PDF
Apache Beam de A à Z
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
JDK1.7 features
Java 7, 8 & 9 - Moving the language forward
Scalable and Flexible Machine Learning With Scala @ LinkedIn
WhatsNewNIO2.pdf
Java 7 & 8 New Features
Java 7 Whats New(), Whats Next() from Oredev
5. Ввод-вывод, доступ к файловой системе
New Features Of JDK 7
JRubyKaigi2010 Hadoop Papyrus
Java I/o streams
Power tools in Java
Why is Java relevant? New features of Java8
Golang basics for Java developers - Part 1
Twitter Author Prediction from Tweets using Bayesian Network
Java 7 Features and Enhancements
Scala is java8.next()
Terence Barr - jdk7+8 - 24mai2011
Apache Beam de A à Z
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Ad

More from Dmitry Buzdin (20)

PDF
How Payment Cards Really Work?
PDF
Как построить свой фреймворк для автотестов?
PDF
How to grow your own Microservice?
PDF
How to Build Your Own Test Automation Framework?
PDF
Delivery Pipeline for Windows Machines
PPTX
Big Data Processing Using Hadoop Infrastructure
PDF
JOOQ and Flyway
PDF
Developing Useful APIs
PPTX
Whats New in Java 8
PPTX
Архитектура Ленты на Одноклассниках
PDF
Dart Workshop
PDF
Riding Redis @ask.fm
PDF
Rubylight JUG Contest Results Part II
PDF
Rubylight Pattern-Matching Solutions
PDF
Refactoring to Macros with Clojure
PPTX
Poor Man's Functional Programming
PDF
Rubylight programming contest
PPTX
Continuous Delivery
PPTX
Introduction to DevOps
PDF
Thread Dump Analysis
How Payment Cards Really Work?
Как построить свой фреймворк для автотестов?
How to grow your own Microservice?
How to Build Your Own Test Automation Framework?
Delivery Pipeline for Windows Machines
Big Data Processing Using Hadoop Infrastructure
JOOQ and Flyway
Developing Useful APIs
Whats New in Java 8
Архитектура Ленты на Одноклассниках
Dart Workshop
Riding Redis @ask.fm
Rubylight JUG Contest Results Part II
Rubylight Pattern-Matching Solutions
Refactoring to Macros with Clojure
Poor Man's Functional Programming
Rubylight programming contest
Continuous Delivery
Introduction to DevOps
Thread Dump Analysis

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
KodekX | Application Modernization Development
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Big Data Technologies - Introduction.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Encapsulation_ Review paper, used for researhc scholars
Advanced methodologies resolving dimensionality complications for autism neur...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Network Security Unit 5.pdf for BCA BBA.
Per capita expenditure prediction using model stacking based on satellite ima...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
KodekX | Application Modernization Development
Digital-Transformation-Roadmap-for-Companies.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
MIND Revenue Release Quarter 2 2025 Press Release
Big Data Technologies - Introduction.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
Understanding_Digital_Forensics_Presentation.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Encapsulation_ Review paper, used for researhc scholars

Jug java7

  • 1. Java 7 new features Java User Group Latvia www.jug.lv
  • 2. Java 7 Project began in August 2006 JDK7 is done via Open JDK effort Major release – JVM, language and library changes Current status – milestone M10, build b115, planned release Mid 2011
  • 3. Initially planned features Closures – Project Lambda Small language changes – Project Coin Modularity for Java platform – Project Jigsaw Support for dynamically-typed languages Core and IO library extensions Swing and UI related changes Support for updated standards - Unicode, localization, security, cryptography, XML and JDBC
  • 4. Two release plans Plan A All features, release in Mid 2012 Plan B JDK 7 minus Lambda, Jigsaw and part of Coin, release in Mid 2011 JDK 8, release in late 2012
  • 5. Plan B selected Plan A All features, release in Mid 2012 Plan B JDK 7 minus Lambda, Jigsaw and part of Coin, release in Mid 2011 JDK 8, release in late 2012
  • 6. Approved feature list JSR 292: Support for Dynamically-Typed Languages (“InvokeDynamic”) Small Language Enhancements (Project Coin) Concurrency and Collections Updates (including the Fork/Join Framework) Upgrade Class-Loader Architecture Unicode 6.0 JSR 203: More New I/O APIs (“NIO 2”) Updated cryptography JDBC 4.1 Translucent & Shaped Windows Heavyweight/Lightweight Component Mixing Swing: Nimbus Look-and-Feel, JLayer Component Update the XML Stack (JAXP, JAXB, & JAX-WS)
  • 7. Language enhancements - Project Coin
  • 8. Strings in switch statement GregorianCalendar c = new GregorianCalendar(); 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": return 28 + (c.isLeapYear(year) ? 1 : 0); default: return -1; } }
  • 9. Improved Type Inference for Generic Instance Creation Map<Integer, List<String>> map = new HashMap<Integer, List<String>>(); New “diamond” operator: Map<Integer, List<String>> map = new HashMap<>(); List<?> l = new ArrayList<>();
  • 10. Try-with-resources void copy(String src, String dest) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dest); try { byte[] buf = new byte[8 * 1024]; int n; while ((n = in.read(buf)) >= 0) out.write(buf, 0, n); } finally { out.close(); } } finally { in.close(); } }
  • 11. Try-with-resources void copy(String src, String dest) throws IOException { 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); } }
  • 12. Try-with-resources void copy(String src, String dest) { 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); } catch (IOException e) { e.printStackTrace(); } }
  • 13. Try-with-resources package java.lang; public interface AutoCloseable { void close() throws Exception; } package java.io; public interface Closeable extends AutoCloseable { void close() throws IOException; }
  • 14. Multi-catch try { String.class.newInstance(); } catch (final IllegalAccessException | InstantiationException e) { e.printStackTrace(); throw e; } catch (Exception e) { // handle exception }
  • 15. Integer and binary literals byte b = 0b00100101; int phoneNumber = 123_456_7890; long creditCardNumber = 1234_5678_9012_3456L; int hexBytes = 0xFF_EC_DE_5E;
  • 16. Simplified Varargs Method Invocation List<String> a = new ArrayList<String>(), b = new ArrayList<String>(), c = new ArrayList<String>(); // Warning: [unchecked] unchecked generic array // creation for varargs parameter of type // List<String>[] return Arrays.asList(a, b, c);
  • 18. Language enhancements in Java 8 Collection literals and indexing List<String> cities = ["Riga", "London", "Tokio"]; Set<String> countries = { "LV", "LT", "EE" }; Map<String, Double> atomicWeights = { "H" : 1.0079, "He" : 4.0026, "Li" : 6.941 }; String city = cities[0]; Double weight = atomicWeights["H"];
  • 19. Language enhancements in Java 8 Closures #{ int x -> x + 1 } #{ System.out.println("Hello, World!") } list.forEach(#{ e -> System.out.println(e) }); Arrays.sort(array, #{ a, b -> a.compareToIgnoreCase(b) });
  • 20. Language enhancements in Java 8 Method references class Person { public static int compareByAge(Person a, Person b) { ... } } Person[] people = ... Arrays.sort(people, #Person.compareByAge); Arrays.sort(people, #Person.compareByAge(Person, Person)); Arrays.sort(people, #comparatorHolder.comparePersonByAge);
  • 21. JSR 292 – Support for Dynamically- Typed languages
  • 22. JSR 292 - Overview Dynamic languages on the JVM JSR 223 implemented in JDK6 JVM initially designed for statically-typed language 4 bytecode instructions available for method invocations Invokestatic Invokevirtual Invokespecial Invokeinterface new bytecode instruction "invokedynamic“ and Method Handles java.dyn package
  • 23. JSR 292 – Method Handles Method handle is a lightweight pointer or reference to a method java.dyn.MethodHandle Example public void testMethodHandle() throws Throwable { MethodHandle hndl = MethodHandles.lookup().findVirtual( PrintStream.class, "println", MethodType.methodType(void.class, String.class)); hndl.<void>invokeGeneric(System.out, "Hello, MethodHandle!"); }
  • 24. JSR 292 Invokedynamic – how it works? JVM encounters invokedynamic instruction JVM invokes the bootstrap method The Bootstrap method resolves the method handle The Bootstrap method must be previously registered in JVM Future calls don't require the Bootstrap method invocation
  • 25. JSR 292 InvokeDynamic, Java example public void testDynamic() throws Throwable { InvokeDynamic.<void>greet("World"); } static { Linkage.registerBootstrapMethod("bootstrap"); } public static void greet(String str) { System.out.println("Hello, dynamic " + str); } private static CallSite bootstrap(Class caller, String name, MethodType type) { CallSite site = new CallSite(caller, name, MethodType.make(void.class)); site.setTarget(MethodHandles.lookup().findStatic(Test.class, name, MethodType.make(void.class, String.class))); return site; }
  • 26. NIO.2
  • 27. NIO.2 – Paths java.nio.file.Path – a replacement for java.io.File File file = new File("index.html"); Path path = Paths.get("index.html"); Path path = new File("index.html").toPath(); All Path methods throw exceptions in case of errors if (!file.delete()){ ... } try { path.delete(); } catch (IOException e) { ... }
  • 28. NIO.2 – FileSystem Provides interface to file system Default file system is local/platform file system FileSystem local = FileSystems.getDefault(); Path p = local.getPath(“filename"); Path p2 = Paths.get(“filename”); Jar and Zip file systems included
  • 29. NIO.2 – DirectoryStream DirectoryStream to iterate over the entries Scales to large directories Filter using glob, regex, or custom filter try (DirectoryStream<Path> stream = dir.newDirectoryStream("*.{c,h,cpp,hpp,java}")) { for (Path entry : stream) { ... } }
  • 30. NIO.2 - Files.walkFileTree Walks a file tree rooted at a given starting file Invoke FileVisitor method for each file/directory interface FileVisitor<T> { FileVisitResult preVisitDirectory(T dir); FileVisitResult visitFile(T file, BasicFileAttributes attrs); FileVisitResult visitFileFailed(T file, IOException exc); FileVisitResult postVisitDirectory(T dir, IOException exc); } SimpleFileVisitor – a default implementation
  • 31. NIO.2 - File change notifications Current approach – polling the file system WatchService – watch registered objects (Watchables) for changes WatchService watcher = path.getFileSystem().newWatchService(); path.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); for (;;) { WatchKey watchKey = watcher.take(); for (WatchEvent event : watchKey.pollEvents()) { System.out.println(event.kind() + " : “ + event.context()); } watchKey.reset(); }
  • 33. Fork/Join Framework Multicore era approaching Moore’s Law doesn’t work since ~2003 Current solution (java.util.concurrent) has its limitations Coarse grained parallelism Inefficient CPU utilization Solution: Fork/Join framework
  • 34. Fork/Join – Divide and conquer Result solve(Problem problem) { if (problem.size < SEQUENTIAL_THRESHOLD) return solveSequentially(problem); else { Result left, right; INVOKE-IN-PARALLEL { left = solve(extractLeftHalf(problem)); right = solve(extractRightHalf(problem)); } return combine(left, right); } }
  • 35. Fork/Join - architecture ForkJoinExecutor, ForkJoinTask Each worker thread has it’s own task queue (deque) – no concurrency between treads for tasks Work stealing algorithm – threads are never idle
  • 36. Fork/Join - ParallelArray ParallelArray<T>, ParallelLongArray etc. Supports filtering, mapping, searching, sorting, reducing etc.
  • 37. ParallelArray example ParallelArray<Order> orders = new ParallelArray<>(fjPool, data); double maxAmount = orders .withFilter(madeThisYear) .withMapping(getAmount) .max(); static final Ops.Predicate<Order> madeThisYear = new Ops.Predicate<>() { public boolean op(Order o) { return o.getYear() == thisYear; } }; static final Ops.ObjectToDouble<Order> getAmount = new Ops.ObjectToDouble<>() { public double op(Order o) { return o.getAmount(); } };
  • 38. Try it yourself Download JDK 7 early access https://jdk7.dev.java.net/