Java SE 7 Preview
Alex Miller
Blog: [Link]
Twitter: [Link]
History
Nov, 2008
Feb, 2002 Sept, 2004 Dec, 2006 Java SE 6 ??
J2SE 1.4 J2SE 5.0 Java SE 6 Update 10 Java SE 7
2002 2003 2004 2005 2006 2007 2008 2009 2010
assert generics scripting support Java Kernel
regular expressions annotations JAX-WS Java Quick Starter
IPv6 autoboxing Java compiler API Nimbus LAF
NIO enumerations pluggable annotations Java Plugin NG
Logging API synth LAF SwingWorker, etc
Image I/O API enhanced for loop
XML/XSLT varargs
Security/crypto Java Memory Model
Java Web Start concurrent library
static imports
Full Menu
Modularity Types and Generics
• Project Jigsaw • Reified Generics
• JSR 294 Superpackages • Type Literals
Libraries • JSR 308 Annotations on Java Types
• JSR 203 NIO2 • Type Inference
• JSR 275 Units and Quantities Language Proposals
• JSR 310 Date and Time API • Closures
• JSR 166 Concurrency Utilities • Automatic Resource Mgmt Blocks
• JSR 225 XQuery API for Java • Language level XML support
• JSR 284 Resource Consumption Mgmt • JavaBean property support
Swing • BigDecimal operator support
• JSR 296 Swing Application Framework • Strings in switch statements
• JSR 295 Beans Binding • Comparisons for Enums
• JSR 303 Beans Validation • Chained invocation
• Java Media Components • Extension methods
JMX • Improved catch
• JSR 255 JMX 2.0 • Null handling improvements
• JSR 262 Web Services Connector JVM
• invokedynamic
Tools
• JSR 326 Post-mortem JVM Diagnostics API • Tiered compilation
• JSR 260 Javadoc Update • G1 garbage collector
Who Decides?
Danny Coward
...and of course the
Java SE 7 JSR
Expert Group
Status du jour
Modularity Types and Generics
• Project Jigsaw YES • Reified Generics NO
• JSR 294 Superpackages YES • Type Literals NO
Libraries • JSR 308 Annotations on Java Types YES
• JSR 203 NIO2 YES • Type Inference YES?
• JSR 275 Units and Quantities NO? Language Proposals
• JSR 310 Date and Time API HMM • Closures NO
• JSR 166 Concurrency Utilities YES • Automatic Resource Mgmt Blocks NO
• JSR 225 XQuery API for Java YES? • Language level XML support NO
• JSR 284 Resource Consumption Mgmt NO • JavaBean property support NO
Swing • BigDecimal operator support NO
• JSR 296 Swing Application Framework YES • Strings in switch statements HMM
• JSR 295 Beans Binding NO • Comparisons for Enums HMM
• JSR 303 Beans Validation HMM • Chained invocation HMM
• Java Media Components YES? • Extension methods HMM
JMX • Improved catch YES?
• JSR 255 JMX 2.0 YES • Null handling improvements YES?
• JSR 262 Web Services Connector YES JVM
• invokedynamic YES
Tools
• JSR 326 Post-mortem JVM Diagnostics HMM • Tiered compilation HMM
• JSR 260 Javadoc Update NO • G1 garbage collector YES
• Compressed pointer 64 bit VM YES
Focus
Modularity JMX
• Project Jigsaw • JSR 255 JMX 2.0
• JSR 294 Superpackages • JSR 262 Web Services
Libraries Connector
• JSR 203 NIO2 Language Proposals
• JSR 310 Date and Time API • Strings in switch
• JSR 166 Concurrency Utilities • Comparisons for Enums
Swing • Chained invocation
• JSR 296 Swing Application • Extension methods
Framework • Improved catch
• JSR 303 Beans Validation • Null handling
• Type Inference
JVM
• invokedynamic
Java Modularity
• JSR 294: [Link]
• Project: [Link]
modules
JAR Hell
Jar Hell in Action
Dependency management is one of the
most important (and challenging) features
of modern software development
Module Development
[Link]
// org/foo/api/[Link]:
[Link]
module [Link];
package [Link];
[Link]
public class FooFighters {
public static FooFighters newBand() {
[Link]
return new [Link]();
}
}
[Link]
Module Development
[Link]
// org/foo/impl/[Link]:
[Link]
module [Link];
package [Link];
[Link]
module class FooFightersImpl
implements FooFighters {
[Link]
// etc
}
[Link]
Module Development
// org/foo/[Link]:
[Link]
@Version(“2.3”)
@MainClass(“[Link]”)
@ImportModules {
[Link]
@ImportModule(name=”[Link]”,
version=”1.7+”)
@ImportModule(name=”[Link]”,
[Link]
version=”1.0”, reexport=”true”)
}
@ExportResources({“org/foo/icons/**})
[Link]
module [Link];
[Link]
Packaging
javac ... // as usual
jam cvf [Link]
org/foo/*
org/foo/api/*
org/foo/impl/*
org/foo/domain/*
org/foo/util/*
JAM Contents
/META-INF/[Link] // Normal jar manifest
/MODULE-INF/[Link] // Module metadata
/MODULE-INF/bin/[Link] // Native libs
/MODULE-INF/bin/[Link]
/MODULE-INF/bin/[Link] // Other jars
/org/foo/[Link] // Compiled module info
/org/foo/**.class // Normal class files
/org/foo/icons // Resources
Module Resolution
Module A Bootstrap Bootclasspath
(1.0)
Extension ESOM
Module B Module C
(2.0) (4.1)
Global Classpath
Module C
(3.2)
OSGi Maven URL
Project Jigsaw
• Modularize the JDK itself
• Integrate at low level
• Integrate with native packaging
• NOT a JSR but part of JDK 7
NIO 2
• JSR 203: [Link]
• Project: [Link]
NIO 2 Themes
• New file system API
• Asynchronous I/O on sockets and files
• Completion of socket channel work
[Link] problems
• Many methods return boolean
• No copy / move support
• No symbolic link support
• No change notification support
• Limited support for file attributes
• Not extensible
New file system API
• FileRef - represents file object in system
• Path - extends FileRef, binds a file to a
system-dependent location
• FileSystem - interface to file system
• FileStore - underlying storage system
File System API
AttributeView
WatchKey WatchEvent
File
WatchService Watchable AttributeView
BasicFile Named
FileRef
AttributeView AttributeView
Directory
FileSystems FileSystem Path Stream
Files
FileStore Paths
FileVisitor
Directory Directory
StreamFilters [Link]
FileVisit
Result
Using Path
import [Link].*;
// FileSystems -> FileSystem -> Path
FileSystem fileSystem = [Link]();
Path homeDir = [Link](“/Users/amiller”);
// Shortcut with Paths helper class
Path homeDir = [Link](“/Users/amiller”);
// Resolve one path in terms of another
Path relativeTemp = [Link](“temp”);
Path absoluteTemp = [Link](homeDir);
// Get relative path from a base
Path absoluteProfile = [Link](“/Users/amiller/.profile”);
Path relativeProfile = [Link](homeDir);
assert [Link]();
assert [Link]() == 1;
Appending to a file
import [Link].*;
import [Link].*;
import static [Link].*;
Path journal = [Link]("/Users/amiller/[Link]");
OutputStream stream =
[Link](CREATE, APPEND);
try {
writeEntry(stream); // normal stuff
} finally {
[Link]();
}
Copying and Moving
import [Link].*;
Path home = [Link]("/Users/amiller");
Path secrets = [Link]("[Link]");
// Steal secrets
[Link]([Link]("[Link]"));
// Hide secrets
[Link]([Link]("/Users/dvader/[Link]"));
Walking Directories
Path music = [Link]("/Users/amiller/files/music");
// External iterator
DirectoryStream<Path> mp3s =
[Link](“*.mp3”);
try {
for(Path entry : mp3s)
[Link]([Link]());
} finally {
[Link]();
}
// Internal iterator
[Link](music, “*.mp3”, new FileAction<Path>() {
public void invoke(Path entry) {
[Link]([Link]());
}
});
Recursive Walk
Path itunes =
[Link]("/Users/amiller/Music/iTunes/iTunes Music");
public class Mp3Visitor extends SimpleFileVisitor<Path> {
private Path root;
public Mp3Visitor(Path root) {
[Link] = root;
}
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
[Link]([Link](file));
}
}
[Link](itunes, new Mp3Visitor(itunes));
File Attributes
Path file = [Link](“/usr/bin/perl”);
// true here means follow symbolic links
BasicFileAttributes attrs =
[Link](file, true);
Set<PosixFilePermission> perms = [Link]();
[Link]("%s %s %s",
[Link](perms),
[Link](),
[Link]());
// rwxr-xr-x root wheel
Watchers
import static [Link].*;
Path deploy = [Link](“deploy”);
WatchService watcher=[Link]().newWatchService();
WatchKey key = [Link](watcher,
ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
for(;;) {
key = [Link](); // blocks, also can poll
for(WatchEvent<?> ev : [Link]()) {
switch([Link]()) {
case ENTRY_CREATE:
Path file = (Path)[Link](); //relative to deploy
// deploy new stuff
case ENTRY_MODIFY: ...
case ENTRY_DELETE: ...
}
}
[Link](); // reset after processing
}
What else?
• NetworkChannel
• finish work on channel to network socket
• Multicasting
• DatagramChannel (now supports),
• AsynchronousDatagramChannel (new)
• Asynchronous I/O for files and sockets
• Future or callback style
• Group support - manage thread pools
Date & Time
• JSR 310: [Link]
• Project: [Link]
• Wiki: [Link]
DateTimeAPI
A simple example
Date xmasEve = new Date(2008, 12, 25, 23, 59, 59);
Is this right?
A simple example
Date xmasEve = new Date(2008, 12, 25, 23, 59, 59);
Is this right?
NO!
Correction:
int year = 2008 - 1900;
int month = 12 - 1;
Date xmasEve = new Date(year, month, 25, 23, 59, 59);
Other Problems
• Date, Calendar, SimpleDateFormatter are mutable
• [Link]() exception handling
• GregorianCalendar time + zone constructor
• Calendars can’t be formatted
• [Link], Time, Timestamp subclass poorly
• Formatters can’t format Timestamp nanos
• Date does not represent a date
Continuous
Instants, Intervals, and
Durations
// Create some instants in seconds
Instant start2008 = [Link](1199167200);
Instant start2009 = [Link](1230789600);
assert [Link](start2009);
// Create an interval - [inclusive, exclusive] by default
InstantInterval year2008 =
[Link](start2008, start2009);
assert [Link](start2008);
assert ! [Link](start2009);
// Create a duration in seconds
Duration minute = [Link](60);
Duration hour = [Link](60);
Duration duration2008 = [Link](
start2008, start2009);
Human
+
Local*, Offset*, Zoned*
// Local human-scale (not tied to TimeZone or Instant)
LocalDate myBirthday =
[Link](1974, [Link], 1);
LocalTime quittingTime = [Link](17, 0);
LocalDateTime start2008 = [Link](
2008, [Link], 1);
// Tie to time zone offset of -6 hours from UTC
OffsetDateTime start2008Offset = [Link](
start2008, [Link](-6));
// Tie to current local time zone
ZonedDateTime start2008Zoned = [Link](
start2008, [Link]().timeZone());
Clock
// Use pre-defined system clock usually
Clock clock = [Link]();
// Create instant
Instant now = [Link]();
// Create human date / time
LocalDate today = [Link]();
Controlling time
LocalDateTime y2k = [Link](
1999, [Link], 31,
23, 59, 59, 999999999);
ZonedDateTime y2kHere = [Link](
y2k, [Link]().timeZone() );
Instant y2kInstant = [Link]();
// Mock around the Clock to test y2k transition
Clock clock = new [Link](y2kInstant);
Other cool stuff
• Matchers, Adjusters, Resolvers
• Full time zone rule support
• Periods: “8 years, 2 months”
• Formatting and parsing
Integration
• Date, Calendar, etc - retrofit with interfaces
• JDBC - map to SQL types
• XML Schema - based on same standard so
should be straightforward
Fork / join
• JSR 166y: [Link]
• Project: [Link]
concurrency-interest/[Link]
Divide and Conquer
Task: Find max value in an array
Divide and Conquer
Divide and Conquer
Divide and Conquer
ParallelArray
import static Ops.*;
ForkJoinPool fj = new ForkJoinPool(10);
Order[] data = ...
ParallelArray<Order> orders = new ParallelArray(fj, data);
ParallelArray
import static Ops.*;
// Filter
[Link]<Order> isLate = new [Link]<Order>() {
public boolean op(Order o) {
return [Link]() < new Date();
}
};
// Map
[Link]<Order> daysOverdue =
new [Link]<Order>() {
public int op(Order o) {
return daysOverdue([Link]());
}
};
ParallelArray
SummaryStatistics<Integer> summary =
[Link](isLate)
.withMapping(daysOverdue)
.summary();
[Link](“overdue: “ + [Link]());
[Link](“avg by: “ + [Link]());
Swing App Framework
• JSR 296: [Link]
• Project: [Link]
Swing Application
Framework
Application
initialize(String[])
startup() Action Application
@Action
shutdown() Manager ActionMap
exit()
SingleFrame Resource Resource Resource
Application Manager Map Converter
Session
Storage
Application
Context
Local
Storage SwingWorker
Task Task
Task
Monitor Service
Beans Validation
• JSR 303: [Link]
Constraints and
Validators
• JavaBeans property validation
• Meta-annotation for defining constraint
annotations
• Core Constraint classes
Constraints
@ZipCodeCityCoherenceChecker // works on Address itself
public class Address {
@NotNull @Length(max=30)
private String addressline1;
@Length(max=30)
private String addressline2;
private String zipCode;
private String city;
@NotNull @Valid // check object graph
private Country country;
@Length(max=30) @NotNull
public String getCity() { ... }
// normal getters and setters
}
Validation
Validator<Address> addressValidator = ...
Address address = ...
// Validate all properties
Set<InvalidConstraint<Address>> invalidItems =
[Link](address);
// Validate specific property
Set<InvalidConstraint<Address>> invalidItems =
[Link](address, “city”);
// Validate potential value for a property
Set<InvalidContraint<Address>> invalidItems =
[Link](“city”, “St. Louis”);
JMX 2.0
• JSR 255: [Link]
• JSR 262: [Link]
• Project: [Link]
Features
• JMX 2.0 (JSR 255)
• Retrofit with generics
• Use annotations
• Make Open MBeans easier to use
• Generalize monitors to support non-simple types
• Cascaded/federated MBean servers
• Web services connector (JSR 262)
Language Changes
• Project Coin
Strings in switch
static boolean isStooge(String stooge) {
switch(input) {
case “Moe”:
case “Curly”:
case “Larry”:
case “Shemp”:
return true;
default:
return false;
}
}
Enum Comparisons
enum Rank {
LIEUTENANT, CAPTAIN, MAJOR, COLONEL, GENERAL
}
Enum Comparisons
enum Rank {
LIEUTENANT, CAPTAIN, MAJOR, COLONEL, GENERAL
}
// Compare using either compareTo() or ordinals
if([Link](rank2) < 0) ...
if([Link]() < [Link]()) ...
Enum Comparisons
enum Rank {
LIEUTENANT, CAPTAIN, MAJOR, COLONEL, GENERAL
}
// Compare using either compareTo() or ordinals
if([Link](rank2) < 0) ...
if([Link]() < [Link]()) ...
// With enum comparison support can instead do:
if(rank1 < rank2) ...
Chained Invocation
// Construction with setters
DrinkBuilder margarita = new DrinkBuilder();
[Link](“tequila”);
[Link](“orange liqueur”);
[Link](“lime juice”);
[Link]();
[Link]();
Drink drink = [Link]();
Chained Invocation
// Construction with setters
DrinkBuilder margarita = new DrinkBuilder();
[Link](“tequila”);
[Link](“orange liqueur”);
[Link](“lime juice”);
[Link]();
[Link]();
Drink drink = [Link]();
// Construction with chained invocation
Drink margarita = new DrinkBuilder()
.add(“tequila”)
.add(“orange liqueur”)
.add(“lime juice”)
.withRocks()
.withSalt()
.drink();
Extension Methods
// I wish List had a sort() method...
List list = new ArrayList();
...
[Link](list); // works for now
[Link](); // ERROR but cleaner
Extension Methods
// I wish List had a sort() method...
List list = new ArrayList();
...
[Link](list); // works for now
[Link](); // ERROR but cleaner
// Maybe we can add it later!
import static [Link];
List list = new ArrayList();
...
[Link](); // now this works!
// equivalent to [Link](list);
Exception boilerplate
// too much boilerplate!!!
} catch(RedException e) {
[Link]([Link](), e);
throw e;
} catch(BlueException e) {
[Link]([Link](), e);
throw e;
}
Exception boilerplate
// too much boilerplate!!!
} catch(RedException e) {
[Link]([Link](), e);
throw e;
} catch(BlueException e) {
[Link]([Link](), e);
throw e;
}
// Catch common superclass???
} catch(Exception e) {
[Link]([Link](), e);
throw e;
}
Multi-catch
public void foo()
throws RedException, BlueException {
try {
...
// Use , to catch multiple types
} catch(RedException, BlueException e) {
[Link]([Link](), e);
throw e;
}
}
Safe Rethrown
public void foo()
throws RedException, BlueException {
try {
...
} catch(final Throwable e) {
[Link]([Link](), e);
throw e;
}
}
Null Handling
Car car = ...
Integer tilt = null;
if(car != null) {
Sunroof sunroof = [Link]()(;
if(sunroof != null) {
tilt = [Link]();
}
}
Integer tilt = car?.getSunroof()?.getTilt();
Type Inference
Map<String, Integer> map =
new HashMap<String, Integer>();
Map<String, Integer> map =
new HashMap<>();
JVM
• Dynamic language support (JSR 292)
• Method handles
• Interface injection?
• Tail recursion?
• G1 garbage collector
Favorites?
What was your favorite library change?
What was your favorite language change?
What’s missing?
Learn more...
• [Link]
• [Link]
Find Me...
• [Link]
• Twitter: @puredanger