The document discusses new features in Java SE 7 including the Fork/Join framework for parallel programming, language evolutions through Project Coin such as try-with-resources statements, and diamond syntax for generic types which simplifies generic class instance creation. It also covers varargs syntax simplification and restrictions on using diamond syntax with anonymous inner classes.
6. class Sum implements Callable<Long> {
private final long from;
private final long to;
Sum(long from, long to) {
this.from = from;
this.to = to;
}
public Long call() {
long acc = 0;
for (long i = from; i <= to; i++) {
acc = acc + i;
}
return acc;
}
}
7. ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<Long>> results = executor.invokeAll(asList(
new Sum(0, 10),
new Sum(100, 1000),
new Sum(10000, 1000000)
));
for (Future<Long> result : results) {
System.out.println(result.get());
}
8. 1.0 Threads made easy
1.1
1.2
1.3
1.4
5 Concurrency made easier
6
7 Parallelism made easier
9. Sum of an array
n1 n2 n3 n4 n5 n6 n7 n8 n9 ... ... ... ...
sum1 sum2 sum3
sum1 + sum2 sum3 + (...)
total sum
13. 16
Folder word
counting task
10
5
1
Document word Document word Folder word
counting task counting task counting task
3 2
fork()
Document word Document word
n join() counting task counting task
14. class FolderSearchTask extends RecursiveTask<Long> {
(...)
protected Long compute() {
long count = 0L;
List<RecursiveTask<Long>> forks = new LinkedList<>();
for (Folder subFolder : folder.getSubFolders()) {
FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
forks.add(task);
task.fork();
}
for (Document document : folder.getDocuments()) {
DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
forks.add(task);
task.fork();
}
for (RecursiveTask<Long> task : forks) {
count = count + task.join();
}
return count;
}
(...)
}
15. class FolderSearchTask extends RecursiveTask<Long> {
(...)
protected Long compute() {
long count = 0L;
List<RecursiveTask<Long>> forks = new LinkedList<>(); Split
for (Folder subFolder : folder.getSubFolders()) {
FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
forks.add(task);
task.fork();
}
for (Document document : folder.getDocuments()) {
DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
forks.add(task);
task.fork();
}
for (RecursiveTask<Long> task : forks) {
count = count + task.join();
}
return count;
}
(...)
}
16. class FolderSearchTask extends RecursiveTask<Long> {
(...)
protected Long compute() {
long count = 0L;
List<RecursiveTask<Long>> forks = new LinkedList<>();
for (Folder subFolder : folder.getSubFolders()) {
FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
forks.add(task);
}
task.fork();
Fork
for (Document document : folder.getDocuments()) {
DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
forks.add(task);
task.fork();
}
for (RecursiveTask<Long> task : forks) {
count = count + task.join();
}
return count;
}
(...)
}
17. class FolderSearchTask extends RecursiveTask<Long> {
(...)
protected Long compute() {
long count = 0L;
List<RecursiveTask<Long>> forks = new LinkedList<>();
for (Folder subFolder : folder.getSubFolders()) {
FolderSearchTask task = new FolderSearchTask(subFolder, searchedWord);
forks.add(task);
task.fork();
}
for (Document document : folder.getDocuments()) {
DocumentSearchTask task = new DocumentSearchTask(document, searchedWord);
forks.add(task);
task.fork();
}
for (RecursiveTask<Long> task : forks) {
count = count + task.join();
}
return count; Join, Compose
}
(...)
}
20. No I/O
No synchronization / locks
Decompose in simple recursive tasks
Do not decompose below a threshold
Take advantage of multicores with no pain
You have more F/J candidate algorithms than
you think!
22. private void writeSomeData() throws IOException {
DataOutputStream out = new DataOutputStream(new FileOutputStream("data"));
out.writeInt(666);
out.writeUTF("Hello");
out.close();
}
23. private void writeSomeData() throws IOException {
DataOutputStream out = new DataOutputStream(new FileOutputStream("data"));
out.writeInt(666);
out.writeUTF("Hello");
out.close();
}
what if...
24. private void writeSomeData() throws IOException {
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream("data"));
out.writeInt(666);
out.writeUTF("Hello");
} finally {
if (out != null) {
out.close();
}
}
}
25. private void writeSomeData() throws IOException {
DataOutputStream out = null;
try {
out = new DataOutputStream(new FileOutputStream("data"));
out.writeInt(666);
out.writeUTF("Hello");
} finally {
if (out != null) {
out.close();
}
}
}
...this is still far from correct!
26. try (
FileOutputStream out = new FileOutputStream("output");
FileInputStream in1 = new FileInputStream(“input1”);
FileInputStream in2 = new FileInputStream(“input2”)
) {
// Do something useful with those 3 streams!
// out, in1 and in2 will be closed in any case
out.write(in1.read());
out.write(in2.read());
}
27. public class AutoClose implements AutoCloseable {
@Override
public void close() {
System.out.println(">>> close()");
throw new RuntimeException("Exception in close()");
}
public void work() throws MyException {
System.out.println(">>> work()");
throw new MyException("Exception in work()");
}
}
29. AutoClose autoClose = new AutoClose();
try {
autoClose.work();
} finally {
autoClose.close();
}
>>> work()
>>> close()
java.lang.RuntimeException: Exception in close()
at AutoClose.close(AutoClose.java:6)
at AutoClose.runWithMasking(AutoClose.java:19)
at AutoClose.main(AutoClose.java:52)
30. AutoClose autoClose = new AutoClose();
try {
autoClose.work();
} finally {
autoClose.close();
}
MyException
m asked by Run
>>> work() time Exception
>>> close()
java.lang.RuntimeException: Exception in close()
at AutoClose.close(AutoClose.java:6)
at AutoClose.runWithMasking(AutoClose.java:19)
at AutoClose.main(AutoClose.java:52)
38. try (AutoClose autoClose = new AutoClose()) {
autoClose.work();
}
>>> work()
>>> close()
MyException: Exception in work()
at AutoClose.work(AutoClose.java:11)
at AutoClose.main(AutoClose.java:16)
Suppressed: java.lang.RuntimeException: Exception in close()
at AutoClose.close(AutoClose.java:6)
at AutoClose.main(AutoClose.java:17)
39. public void compress(String input, String output)
throws IOException {
try(
FileInputStream fin = new FileInputStream(input);
FileOutputStream fout = new FileOutputStream(output);
GZIPOutputStream out = new GZIPOutputStream(fout)
) {
byte[] buffer = new byte[4096];
int nread = 0;
while ((nread = fin.read(buffer)) != -1) {
out.write(buffer, 0, nread);
}
}
}
41. Not just syntactic sugar
Clutter-free, correct code
close():
- be more specific than java.lang.Exception
- no exception if it can’t fail
- no exception that shall not be suppressed
(e.g., java.lang.InterruptedException)
50. class SomeClass<T extends Serializable & CharSequence> { }
Non-denotable type
SomeClass<?> foo = new SomeClass<String>();
SomeClass<?> fooInner = new SomeClass<String>() { };
SomeClass<?> bar = new SomeClass<>();
SomeClass<?> bar = new SomeClass<>() { };
51. class SomeClass<T extends Serializable & CharSequence> { }
Non-denotable type
SomeClass<?> foo = new SomeClass<String>();
SomeClass<?> fooInner = new SomeClass<String>() { };
SomeClass<?> bar = new SomeClass<>();
SomeClass<?> bar = new SomeClass<>() { };
No denotable type
to generate a class
72. // 123 in decimal, octal, hexadecimal and binary
byte decimal = 123;
byte octal = 0_173;
byte hexadecimal = 0x7b;
byte binary = 0b0111_1011;
// Other values
double doubleValue = 1.111_222_444F;
long longValue = 1_234_567_898L;
long longHexa = 0x1234_3b3b_0123_cdefL;
73. public static boolean isTrue(String str) {
switch(str.trim().toUpperCase()) {
case "OK":
case "YES":
case "TRUE":
return true;
case "KO":
case "NO":
case "FALSE":
return false;
default:
throw new IllegalArgumentException("Not a valid true/false string.");
}
}
74. public static boolean isTrue(String s) {
String str = s.trim().toUpperCase();
int jump = -1;
switch(str.hashCode()) {
case 2404:
if (str.equals("KO")) {
jump = 3; Bucket
}
break;
(...)
switch(jump) {
(...)
case 3:
case 4:
case 5:
return false;
default: Real code
throw new IllegalArgumentException(
"Not a valid true/false string.");
}
}
75. Oracle Technology Network (more soon...)
Fork and Join: Java Can Excel at
Painless Parallel Programming Too!
http://goo.gl/tostz
Better Resource Management with
Java SE 7: Beyond Syntactic Sugar
http://goo.gl/7ybgr