jug java7

39
Java 7 new features Java User Group Latvia www.jug.lv

Upload: neueda

Post on 10-May-2015

1.885 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: Jug java7

Java 7 new features

Java User Group Latviawww.jug.lv

Page 2: Jug java7

Java 7Project began in August 2006JDK7 is done via Open JDK effortMajor release – JVM, language and library changesCurrent status – milestone M10, build b115, planned release Mid 2011

Page 3: Jug java7

Initially planned featuresClosures – Project LambdaSmall language changes – Project CoinModularity for Java platform – Project JigsawSupport for dynamically-typed languagesCore and IO library extensionsSwing and UI related changesSupport for updated standards - Unicode, localization, security, cryptography, XML and JDBC

Page 4: Jug java7

Two release plansPlan A

All features, release in Mid 2012Plan B

JDK 7 minus Lambda, Jigsaw and part of Coin, release in Mid 2011JDK 8, release in late 2012

Page 5: Jug java7

Plan B selectedPlan A

All features, release in Mid 2012Plan B

JDK 7 minus Lambda, Jigsaw and part of Coin, release in Mid 2011JDK 8, release in late 2012

Page 6: Jug java7

Approved feature listJSR 292: Support for Dynamically-Typed Languages (“InvokeDynamic”)Small Language Enhancements (Project Coin)Concurrency and Collections Updates (including the Fork/Join Framework)Upgrade Class-Loader ArchitectureUnicode 6.0JSR 203: More New I/O APIs (“NIO 2”)Updated cryptographyJDBC 4.1Translucent & Shaped WindowsHeavyweight/Lightweight Component MixingSwing: Nimbus Look-and-Feel, JLayer ComponentUpdate the XML Stack (JAXP, JAXB, & JAX-WS)

Page 7: Jug java7

Language enhancements - Project Coin

Page 8: Jug java7

Strings in switch statementGregorianCalendar 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;

}

}

Page 9: Jug java7

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

Page 10: Jug java7

Try-with-resourcesvoid 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();

}

}

Page 11: Jug java7

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

}

}

Page 12: Jug java7

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

}

}

Page 13: Jug java7

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;

}

Page 14: Jug java7

Multi-catch

try {

String.class.newInstance();

} catch (final IllegalAccessException | InstantiationException e) {

e.printStackTrace();

throw e;

} catch (Exception e) {

// handle exception

}

Page 15: Jug java7

Integer and binary literals

byte b = 0b00100101;

int phoneNumber = 123_456_7890;

long creditCardNumber = 1234_5678_9012_3456L;

int hexBytes = 0xFF_EC_DE_5E;

Page 16: Jug java7

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

Page 17: Jug java7

Language enhancements postponed until Java 8

Page 18: Jug java7

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"];

Page 19: Jug java7

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

Page 20: Jug java7

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

Page 21: Jug java7

JSR 292 – Support for Dynamically-Typed languages

Page 22: Jug java7

JSR 292 - OverviewDynamic languages on the JVMJSR 223 implemented in JDK6JVM initially designed for statically-typed language4 bytecode instructions available for method invocations

InvokestaticInvokevirtualInvokespecialInvokeinterface

new bytecode instruction "invokedynamic“ and Method Handlesjava.dyn package

Page 23: Jug java7

JSR 292 – Method HandlesMethod handle is a lightweight pointer or reference to a methodjava.dyn.MethodHandleExample

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

}

Page 24: Jug java7

JSR 292 Invokedynamic – how it works?

JVM encounters invokedynamic instructionJVM invokes the bootstrap methodThe Bootstrap method resolves the method handleThe Bootstrap method must be previously registered in JVMFuture calls don't require the Bootstrap method invocation

Page 25: Jug java7

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;

}

Page 26: Jug java7

NIO.2

Page 27: Jug java7

NIO.2 – Pathsjava.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) {

...}

Page 28: Jug java7

NIO.2 – FileSystemProvides interface to file systemDefault 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

Page 29: Jug java7

NIO.2 – DirectoryStream

DirectoryStream to iterate over the entriesScales to large directoriesFilter using glob, regex, or custom filter

try (DirectoryStream<Path> stream =

dir.newDirectoryStream("*.{c,h,cpp,hpp,java}")) {

for (Path entry : stream) {

...

}

}

Page 30: Jug java7

NIO.2 - Files.walkFileTree

Walks a file tree rooted at a given starting fileInvoke 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

Page 31: Jug java7

NIO.2 - File change notifications

Current approach – polling the file systemWatchService – 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();}

Page 32: Jug java7

Fork/Join framework

Page 33: Jug java7

Fork/Join FrameworkMulticore era approachingMoore’s Law doesn’t work since ~2003Current solution (java.util.concurrent) has its limitations

Coarse grained parallelismInefficient CPU utilization

Solution: Fork/Join framework

Page 34: Jug java7

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

}

}

Page 35: Jug java7

Fork/Join - architectureForkJoinExecutor, ForkJoinTaskEach worker thread has it’s own task queue (deque) – no concurrency between treads for tasksWork stealing algorithm – threads are never idle

Page 36: Jug java7

Fork/Join - ParallelArrayParallelArray<T>, ParallelLongArray etc.Supports filtering, mapping, searching, sorting, reducing etc.

Page 37: Jug java7

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

}

};

Page 38: Jug java7

Try it yourselfDownload JDK 7 early access https://jdk7.dev.java.net/

Page 39: Jug java7

Questions