You are on page 1of 82

What is New on the

Java Platform?
Jinyoung Kang
Java Architect & Consultant
Sun Microsystems, KOREA
1
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

2
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

3
Java Platform Roadmap at a Glance
Multiple Languages
Modularity
Rich Clients
Java SE 6 Java SE 7

Announce JavaFX SDK


JavaFX

2006 2007 2008


2009

JRE 6u10
'Consumer JRE'
Open Sourcing JavaOpenJDK™ Launch
'It’s not a matter of when but how' JRE 6u5p
'Performance JRE'

4
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

5
Annotations Today
• Annotations on declarations only
> Classes
@Deprecated class Signer { ...
> Methods
@Override boolean equals(...
> Fields
@Id String customerId;
> Locals
@SuppressWarnings(“unchecked”)
List<String> = new ArrayList();

• Proposal: Allow annotations on type uses

6
JSR 308 – Annotations on Java Types
Two problems with annotations in Java 1.5:
1. Syntactic limitation on annotations
• Can only be written on declarations
2. Semantic limitation of the type system
• Doesn't prevent enough bugs

JSR 308 addresses these problems:


• Extends Java programming language syntax to permit
annotations in more locations
• Enables creation of more powerful annotation processors

7
Syntactic problem: Annotations on
declarations only
* Classes
package java.security;
@Deprecated class Signer { ... }
* Methods
@Test void additionWorks() { assert 1 + 1 == 2; }
@Override boolean equals(MyClass other) // warning
* Fields
@CommandLineArg(name="input", required=true)
private String inputFilename;
* Locals/statements
List<Object> objs = ...;
@SuppressWarnings List<String> strings = objs;
* Goal: Write annotations on type uses

8
Semantic problem: Weak type checking
• Type checking prevents many bugs
> int i = “JSR 308”;
• Type checking doesn't prevent enough bugs
> getValue().toString(); // NullPointerException
• Cannot express important properties about code
> Non-null, interned, immutable, encrypted, tainted, ...
• Solution: pluggable type systems
> Design a type system to solve a specific problem
> Annotate your code with type qualifiers
> Type checker warns about violations (bugs)
> Using annotations insulates the language in case we make a
• mistake designing the type system

9
JSR 308 – Annotations on Java Types
• Type checking prevents many bugs, but does
not prevent enough bugs
getValue().toString() //Potential NPE
• Cannot express important properties about code
> Non-null, interned, immutable, encrypted, ...

10
Example of JSR 308
* Generics
List<@NonNull String> stringList;
* Local variables
@NonEmpty List<String> stringList;
* casts
Graph g = new Graph();
... //add nodes and edges
//Now g2 will not be change any more
@Immutable Graph g2 = (@Immutable Graph)g;
* receiver
/** myMarshaller.marshal(myJaxb, myWriter)
* does not modify myMarshaller */
void marshall(@Readonly Object jaxbElement , @Mutable Writer
writer) @Readonly

11
JSR 308: How to get involved
• Web search for "JSR 308" or "Annotations on Java types"
• Completely open mailing list
• Specification document
• Reference implementation (patch to OpenJDK compiler)
• Checkers Framework
> 5 checkers built so far
> @NonNull @Interned @Readonly @Immutable
> Basic checker (for any annotation name)
• Go forth and prevent bugs!

12
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java (JSR )
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

13
Goals of the Java Module System
Access control More classes to deploy Classloaders

Packages Versioning

Development Modules Deployment

Dependency
Interfaces
control

Assertions Distribution
More classes to reuse
format

14
Goals of the Java Module System
Access control
Promote modular programming
First-class module concept in language & VM
Packages Reflective module metadata

Development goals for the Java Module System

Interfaces
Support JDK™ software modularization
Platform Profiles
Assertions Endorsed Standards Override Mechanism

15
Goals of the Java Module System
Address "JAR hell" Classloaders
Better distribution format than JAR files
Enable side-by-side versioning
Simple and predictable runtime model Versioning

Deployment goals for the Java Module System


Dependency
control
Support entire spectrum of Java programs
Repository infrastructure to isolate modules
Distribution
Customizable for different environments format
(e.g. applets) and module systems
16
JSR 277 “Java Module System”
• JSR 294 owned development modules
("superpackages")
• All modularity discussions now happen in JSR
277
> Development modules in the Java language
> Deployment module framework
> Default deployment module system: The JAM Module
System

17
Modularity In Java Today
• Packages
> Package names are hierarchical
> Package memberships are not
• Access control
> public, protected, private, default
> No real control on packages – com.sun packages
> Rely on documentations and comments to describe
official APIs
• Interfaces
> Not always desirable to have all members public

18
A Typical Package hierarchy
org/
netbeans/
core/
Debugger.class
...
utils/
ErrorTracker.class
...
wizards/
JavaFXApp.class
...
addins/
...

19
org.netbeans.core – obvious “unit”
org/
netbeans/
core/
Debugger.class
...
utils/
ErrorTracker.class
...
wizards/
JavaFXApp.class
...
addins/
...

20
org.netbeans.core – conceptual “module”
org/
netbeans/
core/
Debugger.class
...
utils/
ErrorTracker.class
...
wizards/
JavaFXApp.class
...
addins/
...

21
Modules in the Java Language
// org/netbeans/core/Debugger.java
Module concept module org.netbeans.core;
in the language
package org.netbeans.core;
public class Debugger {
... new ErrorTracker() ...
One module has }
many packages
// org/netbeans/core/utils/ErrorTracker.java
module org.netbeans.core;
package org.netbeans.core.utils;
Module access
specified in the module class ErrorTracker {
language module int getErrorLine() { ... }
}
// org/netbeans.core/module-info.java
Module @Version("7.0")
dependencies
specified in the @ImportModule(name="java.se.core",version="1.7+")
language module org.netbeans.core;

22
Compiling and running a Java module
> javac org/netbeans/core/*
> javac org/netbeans/core/utils/*

> java org.netbeans.core.Debugger

23
Impact of modules in the language & VM
• module restricted keyword
• module-info.java for module-level annotations
• package-info.java can declare module membership
• Classfile attribute for module membership
• Classfile flag for "module-private" accessibility
• Module-private accessibility enforced by the Java Virtual
Machine
• javadoc and javap understand modules in .java and
.class files

24
Address "JAR hell" Classloaders
Better distribution format than JAR files
Enable side-by-side versioning
Simple and predictable runtime model Versioning

Deployment goals for the Java Module System

Dependency
control
Support entire spectrum of Java programs
Repository infrastructure to isolate modules
Distribution
Customizable for different environments format
(e.g. applets) and module systems
25
The JAM Module System
• JAva Modules
• A standard file format and predictable runtime model across Java
• SE 7 implementations
> JAR-like file format
> Easy, reflective, extensible metadata
> Deterministic module resolution algorithm to address JAR hell
> Deterministic module initialization algorithm
> Integrated in platform, tools, class libraries ...
• JAM modules are simple to read and write
> Addresses 80% of the problem space, not 95%
> You can make a system better by keeping things out
> Once a feature is added, it can never be removed
> If a feature is left out, it can always be added later

26
JAM metadata
// org/netbeans/core/module-info.java
Version
@Version("7.0")
Main class @MainClass("org.netbeans.core.Main")
@Attribute(name="IDE", value="NetBeans")
Attributes

Module @ImportModules {
dependencies @ImportModule(name="java.se.core",
version="1.7+"),
@ImportModule(name="org.foo.util",
Custom import version="1.0", reexport=true)
policy }
@ImportPolicyClass("org.netbeans.CustomPolicy")
Initializer @ModuleInitializerClass("org.netbeans.core.Init")

Platform specific @PlatformBinding(os="solaris", arch="sparc")


@ExportResources({"icons/**"})
Exported module org.netbeans.core;
resources
27
Compiling and running a JAM module
• javac org/netbeans/core/*
• javac org/netbeans/core/utils/*

• jam cvf org.netbeans.core-7.0.jam


org/netbeans/core/*
org/netbeans/core/utils/*

• java -jam org.netbeans.core-7.0.jam

• cp org.netbeans.core-7.0.jam /netbeans/repository
• java -module org.netbeans.core:6.0+
-repository /netbeans/repository

28
org.netbeans.core-7.0.jam
• /META-INF/MANIFEST.MF Module metadata
• /MODULE-INF/MODULE.METADATA
Native libraries
• /MODULE-INF/bin/xml-windows.dll
• /MODULE-INF/bin/xml-linux.so JAR files
• /MODULE-INF/lib/xml-parser.jar
• /org/netbeans/core/module-info.class
• /org/netbeans/core/Main.class
• /org/netbeans/core/Debugger.class
• /org/netbeans/core/utils/ErrorTracker.class
• /icons/graphics.jpg
Other resources

• .jam.pack.gz extension for Pack200-gzipped JAM module
29
No more JAR hell
• A JAM module definition imports other JAM module definitions by name
• Module resolution finds module definitions to satisfy imports predictably
• Different versions of the "same" module definition (B) can co-exist
• If different versions of a module definition satisfy an import, use the
highest
• A single version of a module definition (E) can be shared between
modules

30
After a JAM module definition is resolved...
• A JAM module instance is created and initialized
• A JAM module instance has its own classloader
• If JAM module definition A imports JAM module definition B, then A's
• classloader delegates to B's classloader for classes exported by B
• Classloading is completely deterministic

31
Address "JAR hell" Classloaders
Better distribution format than JAR files
Enable side-by-side versioning
Simple and predictable runtime model Versioning

Deployment goals for the Java Module System

Dependency
control
Support entire spectrum of Java programs
Repository infrastructure to isolate modules
Customizable for different environments Distribution
format
(e.g. applets) and module systems
32
Module Repositories
• A hierarchy of repositories

Standard modules
from JDK Bootstrap repository

Extension modules Extension repository

Shared modules
per system Global repository

Shared modules User repository


per user

Application-specific Application repository


modules

33
OSGi in the Java Module System
• Recap:
> The Java Module System is a framework
> Defines key abstractions which concrete module systems can support
> Allows different concrete module systems to co-exist and compete
> Invents fundamental concepts missing in existing module systems
> Repository is the key abstraction

• An OSGi container could implement the Repository API


• A JAM module in JDK7 will be able to import an OSGi bundle

34
OSGi can implement the deployment framework

35
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

36
What is a Closure?
• A closure is a function that refers to free
variables in its lexical context
• A function is a block of code with parameters
> May optionally produce a result
• free variables are identifiers used, but not
defined by the closure

Definition from Neal Gafter's 2007 JavaOne presentation 37


Why Closures?
• Allows blocks of code to be treated as data and
reused
> Captures the environment
> Provides a function pointer type of concept
• Reduces the amount of code that you write
> Hides boiler plate code
• Allows you to write methods that behave and
look like control statements in the language

38
Closure Expressions
• With one and two argument
double log = { double x => Math.log(x) }.invoke(10);
int sum = { int x, int y => x + y }.invoke(3, 4); //will return 7

• Does not return any values (void):


{ char c => System.out.println(c); }.invoke('@'); //will print @

• With local variables


{ int n =>
int m = n + 1;
System.out.println(m * m);
}.invoke(3); //will print 16

*
Examples from http://tronicek.blogspot.com/2007/12/closures-closure-is-form-of-anonymous_28.html
39
Function Types
• Defining a closure as a datatype
• { formal parameters => return type }
• Examples of function types
{ int, String => void }
{ => void }

• Function with one argument and returns a String


{int => String} toBinary = { int x =>
Integer.toBinaryString(x)};
System.out.println(toBinary.invoke(11));//will return 1011

*
Examples from http://tronicek.blogspot.com/2007/12/function-types.html
40
Access to Local Variables
static void doTwice({ => void } block) {
block.invoke(); // will print 10
int x = 20;
block.invoke(); // will print 11
System.out.println(x); // will print 20
}

public static void main(String[] args) {


@Shared
int x = 10;
// the block is "packed" with variable x
doTwice({ => System.out.println(x++); });
}
*
Adapted from http://tronicek.blogspot.com/2008/01/completion-transparency.html
41
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

42
Multi-Catch
try { ...
* } catch (X1 e) { foo(); }
} catch (X2 e) { foo(); }
} catch (X3 e) { bar(); }

• A longstanding request to allow catching X1 and X2


together, without resorting to catching Exception itself
try { ...
} catch (X1, X2 e) { foo(); }
} catch (X3 e) { bar(); }
• A disjunctive type X1, X2 represents X1 or X2
> The members of e are those of a common superclass

43
Safe re-throw
void m() throws X1,X2 {
try { /* Something that can throw X1,X2 */ }
catch (Throwable e) {
logger.log(e);
throw e; // Error: Unreported exception Throwable
}
}
* We want to express we're rethrowing the exception in the try{}

void m() throws X1,X2 {


try { /* Something that can throw X1,X2 */ }
catch (final Throwable e) {
logger.log(e);
throw e; // Compiles OK; can throw X1,X2
}
}
44
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

45
AWT Enhancements
• Supports translucent
and shaped windows
• Leverages hardware
acceleration (OpenGL
/ Direct3D) where
available

http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/
46
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

47
Developing Swing Applications Today

public class MySwingApp {

//Good luck
}

48
Swing Application Framework Architecture

Lifecycle
Resources
Actions
Tasks
Session state

49
Swing Application Framework
Application Controller

Data Synchronization

Data Conversion

Data Validation

Actions Resources
Web Service
Data Model
Lifecycle Tasks

Database
Application Framework

50
Framework Components
• Swing Application
Framework – JSR296
Data Synchronization > Lifecycle methods
> Resource injections
Data Conversion
> Maintain application
Data Validation states
> Tasks
• Beans Binding –
Resources Actions JSR295
> Connecting JavaBeans'
Tasks Lifecycle
properties
> Keeping them in sync
http://appframework.dev.java.net
http://beansbinding.dev.java.net 51
Using the Framework (JSR 296)
• Create a subclass of Application
• Create and show your GUI in the startup method
• Use ApplicationContext services to
> define/manage actions and tasks
> load/inject resources
> save/restore session state
• Call Application.launch from your main method

52
Swing Application Framework Example – 1
public class MyApp extends SingleFrameApplication {
@Override protected void startup() {
JLabel label = new JLabel("Hello World");
show(label);
}
public static void main(String[] args) {
Application.launch(MyApp.class, args);
}
}
// SingleFrameApplication is a subclass of Application

53
Application Lifecycle Methods
Calls initialize(), startup(), ready() on EDT thread.

Performs initializations that must happen before the GUI is


created like setting look & feel.

Creates the initial GUI and shows it. All applications will
override this method.

Any work that must wait until the GUI is visible and ready for input.

Calls shutdown() if the exitListeners do not veto. Main frame's


Windowlistener calls exit().

Take the GUI down and do final cleanup.

54
Application Resources
• Defined with ResourceBundles
• Organized in resources subpackges
• Used to initialize properties specific to:
> locale
> platform
> a few related values…

55
ResourcesMaps
• Encapsulate list of ResourceBundles whose
names arebased on a class
• Automatically parent-chained
> Superclass resources
> Application-wide resources
• Support extensible string to type resource
conversion
• Support ${resource key} substitution:

version = 1.0
title = My Application version ${version}

56
Using ResourceMaps: Example
ApplicationContext c = Application.getInstance().getContext()
ResourceMap r = c.getResourceMap(MyForm.class);

r.getString("aFormat", "World") => "Hello World"


r.getColor("colorRBGA") => new Color(5, 6, 7, 8)
r.getFont("aFont") => new Font("Arial", Font.PLAIN, 12)

# resources/MyForm.properties
aString = Just a string
aFormat = Hello %s
anInteger = 123
aBoolean = True
anIcon = myIcon.png
aFont = Arial-PLAIN-12
colorRGBA = 5, 6, 7, 8
color0xRGB = #556677

57
Actions: A (very) brief review
Encapsulation of an ActionListener and:
• some purely visual properties
• enabled and selected boolean properties

// define sayHello Action – pops up message Dialog


Action sayHello = new AbstractAction("Hello") {
public void actionPerformed(ActionEvent e) {
String s = textField.getText();
JOptionPane.showMessageDialog(s);
}
};
// use sayHello – set the action property
textField.setAction(sayHello);
button.setAction(sayHello);

58
Actions: What We Like
• Encapsulation of default GUI + behavior
• The enabled and selected properties
• Reusability

59
The new @Action annotation
// define sayHello Action – pops up message Dialog
@Action public void sayHello() {
String s = textField.getText();
JOptionPane.showMessageDialog(s);
}
// use sayHello – set the action property
Action sayHello = getAction("sayHello");
textField.setAction(sayHello);
button.setAction(sayHello);

• ActionEvent argument is optional


• Used to define a “sayHello” ActionMap entry
• Encapsulation of default GUI + behavior

60
Tasks
• Inherit the SwingWorker API
• Support for monitoring
• Title, Start/Done, etc.
• Asynchronous @Actions return Tasks
• Easy to handle non-blocking actions

61
Asynchronous @Action example
@Action public Task sayHello() { // Say hello repeatedly
return new SayHelloTask();
}
private class SayHelloTask extends Task<Void, Void> {
@Override protected Void doInBackground() {
for(int i = 0; i <= 10; i++) {
progress(i, 0, 10); // calls setProgress()
message("hello", i); // resource defines format
Thread.sleep(150L);
}
return null;
}
@Override protected void succeeded(Void result) {
message("done");
}
@Override protected void cancelled() {
message("cancelled");
}
}

62
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

63
Beans Binding (JSR 295)
• Keeps properties of two objects in sync
• Source properties can specified using
Expression Language:
• ex: “${customer}” or “${employee.salary}”
• Does not require special object types:
• Bindings.createAutoBinding(READ_WRITE,sour
ce,source Prop, target, target Prop);

64
Beans Binding Feature
• Different update strategies
• Read once, read only from source, keep source
and target in sync
• Ability to do validation
• Ability to transform value
• String to Color, Date to String

65
Beans Binding Example – Before 295
faceSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
caricature.setFaceStyle(faceSlider.getValue());
}
});
caricature.addPropertyChangeListener(new
PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName() == “faceStyle”) {
faceSlider.setValue(caricature.getFaceStyle());
}
} });

http://weblogs.java.net/blog/shan_man/archive/2007/09/beans_binding_1.html 66
Beans Binding Example – JSR 295
Property faceStyleP= ELProperty.create(“${faceStyle}”);
Property sliderP = BeanProperty.create(“value”);
Binding binding = Bindings.createAutoBinding(
UpdateStrategy.READ_WRITE,
caricature, faceStyleP, // source
faceSlider, sliderP); // target

binding.bind();

http://weblogs.java.net/blog/shan_man/archive/2007/09/beans_binding_1.html 67
DEMO

68
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

69
File System API
• What's wrong with java.io.File?
> No concept of file systems, attributes, 'link',
storages, ...
• Proposed new API (main classes only)
> FileSystem – factory for objects to access file and
other objects in file system
> FileRef – reference to a file or directory, contains
methods to operate on then
> Path – a FileRef that locates a file by a system
dependent path
> FileStore – underlying storage pool, device,
partition, etc
• http://openjdk.java.net/projects/nio
70
File System API Example – 1
Path home = Path.get(“/home/obiwan”);
//Reference to .bash_profile in /home/obiwan
Path profile = home.resolve(“.bash_profile”);

profile.copyTo(home.resolve(“.bash_profile.backup”));

WritableByteChannel chan =
profile.newSeekableByteChannel(APPEND);

// Append stuff to .bash_profile


...

chan.close();

71
Agenda

● Java Platform Roadmap of a Glance


● Annotations on Java Types (JSR 308)
● Goals of the Java Module System (JSR 277, 294)
● Closure of Java
● Some language features under consideration
● AWT Enhancements
● Swing Application Framework (JSR 296)
● Bean Binding (JSR 295)
● File System API (JSR 203)
● ForkJoin Framework (JSR 166y)
● Summary

72
Hardware trends
• As of ~2003, we stopped seeing increases in CPU clock rate
• Moore’s law has not been
repealed!
> Giving us more cores per chip
rather than faster cores
● Maybe even slower cores
• Chart at right shows clock speed of
Intel CPU releases over time
> Exponential increase until 2003
> No increase since 2003
• Result: many more programmers
become concurrent programmers
(maybe reluctantly)

73
JSR 166y: ForkJoin
• “The free lunch is over”
> No more relying on faster CPUs to compensate for
poor coding
• Multicore CPUs
> Performance improvement only possible by exploiting
these
• Concurrency and parallelism techniques are no
longer confined to HPC realm
• java.util.concurrent.forkjoin package
• Processor hints
> Runtime.availableProcessors()

74
Parallelization technique: divide-and-conquer
• Divide-and-conquer breaks down a problem into subproblems,
• solves the subproblems, and combines the result
• Example: merge sort
> Divide the data set into pieces
> Sort the pieces
> Merge the results
> Result is still O(n log n), but subproblems can be solved in parallel
> Parallelizes fairly efficiently – subproblems operate on disjoint data
• Divide-and-conquer applies this process recursively
> Until subproblems are so small that sequential solution is faster
> Scales well – can keep many CPUs busy

75
Fork-join parallelism
• The key to implementing divide-and-conquer is the invoke-in-parallel
operation
> Create two or more new tasks (fork)
> Suspend the current task until the new tasks complete (join)
• Naïve implementation creates a new thread for each task
> Invoke Thread() constructor for the fork operation
> Thread.join() for the join operation
> Don’t actually want to do it this way
● Thread creation is expensive
● Requires O(log n) idle threads

• Of course, non-naïve implementations are possible


> Package java.util.concurrent.forkjoin proposed for JDK 7 release
offers one
> For now, download package jsr166y from
> http://gee.cs.oswego.edu/dl/concurrency-interest/index.html

76
Solving select-max with fork-join
The RecursiveAction class in the fork-join framework is ideal
for representing divide-and-conqure solutions
class MaxSolver extends RecursiveAction {
private final MaxProblem problem ;
int result;
protected void compute() {
if (problem.size < THRESHOLD)
result = problem.solveSequentially();
else {
int m = problem.size / 2;
MaxSolver left, right;
left = new MaxSolver(problem.subproblem(0, m));
right = new MaxSolver(problem.subproblem(m, problem.size));
forkJoin(left, right);
result = Math.max(left.result, right.result);
}
}
}
ForkJoinExecutor pool = new ForkJoinPool(nThreads);
MaxSolver solver = new MaxSolver(problem);
pool.invoke(solver);

77
Work stealing
• Fork-join framework is implemented using work-stealing
> Create a limited number of worker threads
> Each worker thread maintains a private double-ended work
queue (deque)
● Optimized implementation, not the standard JUC deques
> When forking, worker pushes new task at the head of its deque
> When waiting or idle, worker pops a task off the head of its
deque and executes it
● Instead of sleeping
> If worker’s deque is empty, steals an element off the tail of the
deque of another randomly chosen worker

78
Summary
• Lots of new things coming
• Will make Java applications smaller, more
concise, easier to read (and understand), less
errors
• Lots of nice libraries that are going to exploit the
hardware
• Platform will be more robust and scalable

79
Summary Proposed JSRs for Java SE 7 Platform
• JSR 277: Java Module System
• JSR 294: Improved modularity support in the Java programming language
• JSR 295: Beans binding
• JSR 303: Bean validation
• JSR 292: Supporting Dynamically Typed Languages
• JSR 296: Swing application framework
• JSR 203: More new I/ O APIs for the Java Platform (NIO.2)
• JSR 220: Enterprise JavaBeans™ 3.0
• JSR 255: JMX specification, version 2.0
• JSR 262: Web services connector for JMX agents
• JSR 260: Javadoc™ Tag Technology Update
• JSR(s) TBD Java Language changes
• JSR 308: Annotations on Java Types
• JSR 310: Date and Time API

80
Thank You :-)
Jinyoung Kang
netbeans.korea@gmail.com
http://planetnetbeans.org/ko/index.html

81

:-)
Jinyoung Kang
netbeans.korea@gmail.com
http://planetnetbeans.org/ko/index.ht
ml

82

You might also like