Presentation The Evolution of Java: Past, Present, and Future
The Java programming language has evolved significantly since its introduction in 1995. In this talk, I’ll discuss language changes from the addition of assertions in JDK 1.4 through Project Coin in Java 8, discussing what worked, what didn’t, and why. Finally, I’ll discuss ongoing efforts (Project Lambda for Java 8) and future plans, in light of the lessons learned from previous changes.
Published on: 2011-12-20T07:39:42.000Z
Channel: Devoxx'11 (all)
Tags: Java JDK JDK 1.4 evolution Java 8 javase
Speakers:
Joshua J. Bloch
Joshua J. Bloch is a software engineer, currently a Principal Engineer at Google, and
a technology author. He led the design and implementation of numerous Java platform features,
including the Java Collections Framework, the java.math package, and the assert mechanism. He is
the author of the programming guide Effective Java as well as the co-author of two other Java
books. Joshua Bloch holds a B.S. in Computer Science from Columbia University and a Ph.D. in
Computer Science from Carnegie-Mellon University.
PDF: slides.pdf
Slides:
The Evolution of Java:
The Evolution of Java:
Past, Present, and Future
Joshua Bloch Google
Preliminaries
Preliminaries
· This talk is highly opinionated
Opinions are mine, not my employer's or Miss Piggy's
· This talk contains predictions
Some will almost certainly be wrong
· This talk contains some criticism
All of it is intended to be constructive I still Java
2
Goals
Goals
· Critique every language change from JDK 1.1 to Java 7
Did it make the platform better? Did it preserve "The Feel of Java"? Should we have done anything differently (or excluded the change entirely)?
· How are we doing, and what lessons can we carry forward?
3
OOPSLA Invited Talk October 8, 1996
OOPSLA Invited Talk October 8, 1996
Digitally reconstructed from the Internet Archive (AKA the Wayback Machine) by Joshua Bloch November 24, 2007
Oak
Oak
· Started as a reimplementation of C++ · Always a tool, never an end itself · Took on a life of its own · The Web happened...
· serendipitous match!
· and it became Java
The Java Language
The Java Language
Fusion of four kinds of programming · Object Oriented like Simula/C++/ObjectiveC... · Numeric like FORTRAN · Systems like C · Distributed like nothing else
Java - a language for a job
Java - a language for a job
· Doing language research:
an anti-goal
· Started using C++ · Broke down, needed:
· Architecture neutral, portable, reliable, safe, long lived, multithreaded, dynamic, simple, ...
Practical, not theoretical
Practical, not theoretical
· Driven by what people needed
· (but hey, I spent too much time going to school!)
· Theory provides
· rigour · cleanliness · cohesiveness
No new ideas here
No new ideas here
· Shamelessly ripped off ideas that worked in C, C++, Objective C, Cedar/Mesa, Modula, Simula, ... · (well, we slipped once or twice and invented something)
Don't fix it until it chafes
Don't fix it until it chafes
· To keep it simple... · A procedural principle:
· Require several real instances before including a feature · i.e. nothing goes in because it's "nice"
· (== "Just Say No, until threatened with bodily harm")
· Hyped :-( · Playful · Flexible · Deterministic · Non-threatening · Rich · Like I can just write code...
· Hyped :-( · Playful · Flexible · Deterministic · Non-threatening · Rich · Like I can just write code...
Hey! I left out "Object-Oriented"!
Java feels...
IEEE Computer, June 1997
IEEE Computer, June 1997
Cover Feature
The Feel of Java
Java is a blue collar language. It's not PhD thesis material but a language for a job. Java feels very familiar to many different programmers because we preferred tried-and-tested things.
James Gosling
Sun Microsystems Inc.
J
ava evolved out of a Sun research project started six years ago to look into distributed control of consumer electronics devices. It was not an academic research project studying programming languages: Doing language research was actively an antigoal. For the first three years, I worked on the language and the runtime, and everybody else in the group worked on a variety of different prototype applications, the things that were really the heart of the project. So the drive for changes came from the people who were actually using it and saying "do this, do this, do this." Probably the most important thing I learned in talking to the folks building TVs and VCRs was that their priorities were quite different from ours in the computer industry. Whereas five years ago our mantra was compatibility, the consumer electronics industry considered secure networking, portability, and cost far more important. And when compatibility did become an issue, they limited notions of compatibility to well-defined interfaces-- unlike the computer industry where the most ubiquitous interface around, namely DOS, is full of secret back doors that make life extremely difficult. I've listed the differing priorities for the commercial software and consumer electronics industries in Table 1. One interesting phenomenon that has occurred over the past five years is that con-
sumer electronics business, there are dozens of different CPU types and good reasons for all of them in their individual contexts. But developing software for a dozen different platforms just doesn't scale, and it was this desire for architecture neutrality that broke the C++ mold--not so much C++ the language, but the standard way people built C++ compilers.
BLUE COLLAR LANGUAGE
Java is a
Of Course, There Were Naysayers
Of Course, There Were Naysayers
"Much of the relative simplicity of Java is--like for most new languages--partly an illusion and partly a function of its incompleteness. As time passes, Java will grow significantly in size and complexity. It will double or triple in size and grow implementation-dependent extensions or libraries." -- Bjarne Stroustrup, 2/97
13
Outline
Outline
· Nested Classes (JDK 1.1, 1997) · Strings in switch (Java SE 7, 2011) · Object Serialization · strictfp (J2SE 1.2, 1998) · Assertions (J2SE 1.4, 2002) · Generics (J2SE 5, 2004) · Annotations · Enhanced for loop (for-each) · Autoboxing/unboxing · Varargs · Enums · Static Import
14
· Improved numeric literal syntax · Multi-catch · More precise rethrow · Improved type inference for generic instance creation (<>) · try-with-resources statement · Simplified varargs method invocation · Conclusion
Nested Classes (JDK 1.1, 1997)
Nested Classes (JDK 1.1, 1997)
· Declare classes within classes · Four flavors
static member classes nonstatic member classes anonymous classes local classes (rarely used)
· Two main goals
Confine class scope for better encapsulation Provide a rudimentary closures facility
15
Nested Classes--Example Uses
Nested Classes--Example Uses
// Encapsulation public class MySet extends AbstractSet { ... // Bulk of the class omitted public Iterator iterator() { return new MyIterator(); } private class MyIterator implements Iterator { ... } }
// Closures Arrays.sort(args, new Comparator() { public int compare(String s1, String s2) { return s1.length() - s2.length(); }});
16
Nested Classes Are Nonstatic By Default-- Often Wasteful, Can Be Deadly
Nested Classes Are Nonstatic By Default-- Often Wasteful, Can Be Deadly
public class ThreadFriendly { // Puzzlers: Scraping the Bottom of the Barrel ThreadLocal threadLocalPart = new ThreadLocal(); class Value { // Throws OutOfMemoryError unless Value declared static final int i; Value(int i) { this.i = i; } } ThreadFriendly setThreadVal(int i) { threadLocalPart.set(new Value(i)); return this; // To allow method chaining } int getThreadVal() { return threadLocalPart.get().i; } public static void main(String[] args) { int sum = 0; for (int i = -500000; i < 500000; i++) sum += new ThreadFriendly().setThreadVal(i).getThreadVal(); System.out.println(sum); } }
17
Mixing Inheritance and Nonstatic Nesting is Evil
Mixing Inheritance and Nonstatic Nesting is Evil
public class Outer { class Inner1 extends Outer { } class Inner2 extends Inner1 { } }
Outer.java:3: cannot reference this before supertype constructor has been called class Inner2 extends Inner1 { } ^
See Java Puzzlers 90 "It's Absurd, It's a Pain, It's Superclass!" for details
18
Nested Classes Critique
Nested Classes Critique
· Good for encapsulation; not good enough for closures
Anonymous class syntax should have been better
· Should have been static by default
Nonstatic nested classes should be illegal
PUKE
· Nested classes (still) not supported by VM
private modifier results in invisible synthetic accessor methods People complain about large footprint Arguably these performance issues are implementation details · But they haven't been addressed in 14 years
· Conclusion: not bad, but could have been really good
19
Serialization
Serialization
· Is a language feature, though the JLS tries hard to deny it
· Arrays and enums are serializable · The transient modifier is provided
public class Name implements Serializable { private final String lastName; private final String firstName; private final String middleName; ... // Remainder omitted } // This method is very slow and generally a bad idea! public static Object deepCopy(Object obj) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); new ObjectOutputStream(bos).writeObject(obj); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); return new ObjectInputStream(bin).readObject(); } catch (Exception e) { throw new IllegalArgumentException(e); } }
20
Serialization and Instance Control Don't Get Along Well
Serialization and Instance Control Don't Get Along Well
// Not a Singleton! public class Elvis implements Serializable { public static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } public void leaveTheBuilding() { ... } }
// Not a Singleton! (Puzzler 83, Dyslexic Monotheism) public class Dog extends Exception { public static final Dog INSTANCE = new Dog(); private Dog() { } public String toString() { return "Woof"; } }
There are many more Serialization puzzlers See Effective Java Chapter 11 if you're morbidly curious Also see Java Puzzers 91, "Serial Killer"
21
Serialization Critique
Serialization Critique
· It sort of works... · Implementing Serializable introduces a hidden constructor
Severely harms the programmers's intuition Complicates instance control Opens numerous serious security holes
PUKE
· Default serial form is seductive
Leaks private fields into public API Often performs abysmally (e.g., LinkedList) Sometimes introduces outright bugs (e.g., Hashtable)
· Designing bulletproof readObject methods can be nearly impossible (See Effective Java Item 76, Java Puzzlers 91)
22
Serialization Critique, continued
Serialization Critique, continued
· Serialization and final fields don't mix · Deserialization requires casting, which sacrifices compile-time type safety · serialVersionUID is needless clutter · You can't ignore serialization, even if you aren't using it
PUKE
· Conclusion: arguably the worst feature ever added
23
strictfp modifier (J2SE 1.2, `98)
strictfp modifier (J2SE 1.2, `98)
· Before Java 2, floating point arithmetic was specified to be bit-for-bit reproducible
Had a huge performance cost on x86 processors of the day
· Java 2 legalized larger registers for intermediate results
Allowed these processors to run faster with more accurate results
· But some people still needed (?) bit-for-bit reproducible FP · strictfp mandates pre-Java-2 specified behavior
Can be applied to methods or classes
24
Example Use of strictfp
Example Use of strictfp
public class StrictfpExample { public static strictfp void main(String[] argv) { double d = 8e+307; System.out.println(d * 2); System.out.println(d * 4 * 0.5); } }
· Required to print 1.6E308 Infinity · Modern hardware gives same results without strictfp
25
Critique of strictfp
Critique of strictfp
· Needed for an idiosyncrasy in Intel x87 math coprocessor
Intel deprecated the x87 instruction set in 2000 AMD deprecated the instruction set in 2003 (Replaced by SSE2)
· I know of
Only one Java programmer who has used strictfp in practice No program that is affected by strictfp on modern CPU
· But at least it's very easy to ignore · Conclusion: minor wart that might have been avoided
PUKE
26
Assertions (J2SE 1.4, 2002)
Assertions (J2SE 1.4, 2002)
· Statement with a boolean expression that programmer believes to be true assert mySpeed <= SPEED_OF_LIGHT; · Throws AssertionError if expression is false at runtime · Disabled by default--no performance effect* · Typically enabled during development · May be enabled in field
* Except in rare circumstances; measure if it's critical
27
Example Use of Assertion
Example Use of Assertion
int residue = i % 3; if (residue == 0) { ... } else if (residue == 1) { ... } else { assert residue == 2; ... }
28
Sermon from JavaOne 2001
Sermon from JavaOne 2001
· Accept Assertions Into Your Life!
Easy to add asserts while you're programming They document and test your assumptions They verify your understanding of your code They quickly uncover bugs They ensure that bugs are not introduced in the future Result: higher code quality with lower maintenance cost
29
Sadly, Most Ignored Me--Why?
Sadly, Most Ignored Me--Why?
· I don't know! · Perhaps 2002 was too late
Scala had them from the word go, and everyone uses them
· Maybe I didn't preach enough · Some people are uncomfortable:
Enabling in the field due to cost Or disabling in the field due to possible change in behavior
· Perhaps assertions should have been enabled by default...
But some are afraid of performance costs even when disabled
· Tiny but vocal minority want full design-by-contract facility
Most popular RFE on The Bug Parade for years
30
Assertions Critique
Assertions Critique
· Sadly, most programmers get little benefit in practice · On the bright side, assertions are easy to ignore · There were negative effects at time of introduction
New keyword broke many programs including JUnit Tool vendors howled: change Java substantially or leave it alone
· Conclusion: a net win, but barely
A few of us brave souls use and like them The rest simply ignore them
PUKE
31
Generics (J2SE 5, 2004)
Generics (J2SE 5, 2004)
· Here's what I said at JavaOne 2004 ("Taming the Tiger")
Allow you to specify element type of collection Enforce specification at compile time "Stronger typing with less typing"--No casts! Goes way beyond collections
· I was right except for the part about less typing · But that was only half the story...
32
The Other Half of the Story
The Other Half of the Story
· Enum> { ... } · > T Collections.max(Collection extends T>) · public >> Comparator comparator() { ... } · error: equalTo(Box) in Box cannot be applied to (Box) equal = unknownBox.equalTo(unknownBox)
· See Angelika Langer's 297-page (!) Java Generics FAQ
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.pdf
· Not just API designers, programmers have to deal with it too
33
Only One Feature Ever Generated This Sort of Response
Only One Feature Ever Generated This Sort of Response
"I am completely and totally humbled. Laid low. I realize now that I am simply not smart at all. I made the mistake of thinking that I could understand generics. I simply cannot. I just can't. This is really depressing. It is the first time that I've ever not been able to understand something related to computers, in any domain, anywhere, period." -- A Java Programmer, 2006 "I'm the lead architect here, have a Ph.D. in physics, and have been working daily in Java for 10 years and know it pretty well. The other guy is a very senior enterprise developer (wrote an email system that sends 600 million emails/year with almost no maintenance). If we can't get [generics], it's highly unlikely that the `average' developer will ever in our lifetimes be able to figure this stuff out." -- A Java Programmer, 2006 "[Generics] are a disaster; they have made Java harder to learn and to understand, and you can't avoid them." -- Tim Bray, 2007 "We simply cannot afford another wildcards." -- Doug Lea, 2007
34
Generics Critique
Generics Critique
· Significantly enhanced type-safety and expressiveness · Adding wildcards at last minute was a very bad idea!
Came from recent research paper: Atsushi Igarashi and Mirko Viroli, On Variance-Based Subtyping for Parametric Types, (ECOOP 2002)
· Impedance mismatch with arrays!
Erasure and covariant arrays don't mix
PUKE
· Warnings and errors a fact of life, and nearly unreadable · Even the best programmers don't understand the intricacies · Conclusion: generics essential, but design was wrong
We blew our complexity budget for the language We did significant harm to "The Feel of Java"
35
Annotations
Annotations
· General purpose program metadata facility
Makes it possible to associate data with program entities
· Readable from source files, class files, and reflectively at runtime · Eliminates the need for ad hoc metadata facilities
Naming patterns, Javadoc abuse
36
Example--Test Framework: 1
Example--Test Framework: 1
Annotation Type Declaration
import java.lang.annotation.*; /** * Indicates that the annotated static, * parameterless method is a test method. */ @Retention(RetentionPolicy. RUNTIME) @Target(ElementType.METHOD) public @interface Test { }
37
Example--Test Framework: 2
Example--Test Framework: 2
Annotated Program
public class Foo { @Test public static void m1() { } public static void m2() { } @Test public static void m3() { throw new RuntimeException("Boom"); } public static void m4() { } @Test public static void m5() { } public static void m6() { } @Test public static void m7() { throw new RuntimeException("Crash"); } public static void m8() { } }
38
Example--Test Framework: 3
Example--Test Framework: 3
Testing Tool
import java.lang.reflect.*; public class RunTests { public static void main(String[] args) throws Exception { int passed = 0, failed = 0; for (Method m : Class.forName(args[0]).getMethods()) { if (m.isAnnotationPresent(Test.class)) { try { m.invoke(null); passed++; } catch (Exception ex) { System.out.printf("Test %s failed: %s %n", m, ex.getCause()); failed++; } } } System.out.printf("Passed: %d, Failed %d%n", passed, failed); } }
39
Annotations Critique
Annotations Critique
· Well integrated with the Java platform
Makes good use of interfaces, generics, modifier, etc.
· Enabled many successful projects, such as Guice · @Override has caught many a bug
PUKE
· Of course it isn't perfect
Annotations should be legal on type parameter declarations Default RetentionPolicy should have been RUNTIME One-annotation-per-type restriction is a compromise Some dislike that annotations legal only on declarations; I disagree
· Conclusion: a success; modestly useful to many, critical to some
40
Enums
Enums
· Rich, typesafe, object-oriented enumerated types
enum Stooge { LARRY, MOE, CURLY } public enum Operation { PLUS("+") { double MINUS("-") { double TIMES("*") { double DIVIDE("/") { double apply(double apply(double apply(double apply(double x, x, x, x, double double double double y) y) y) y) { { { { return return return return x x x x + * / y; y; y; y; }}, }}, }}, }};
private final String symbol; Operation(String symbol) { this.symbol = symbol; } @Override public String toString() { return symbol; } abstract double apply(double x, double y); }
41
Enums Critique
Enums Critique
· Combines power of Typesafe Enum pattern with ease-of-use of regular enums
PUKE
· Not perfect
Implicit nested classes from constant-specific class bodies can confuse No way to initialize static fields before constructors run
· Doesn't support inheritance, but I defend this decision · Conclusion: rip roaring success
42
Enhanced for loop (for-each)
Enhanced for loop (for-each)
· Lets you iterate over collections, arrays without using iterators, index variables · Increases clarity and reduces the opportunity for bugs
for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) deck.add(new Card(rank, suit));
· Critique
Accomplished what it set out to do Most love the syntax and semantics Enormous power-to-weight ratio Quibble--these should be legal
·for (char c : someString) ·for (int codePoint : someString)
PUKE
· Conclusion: most successful language change to date
43
Autoboxing and unboxing
Autoboxing and unboxing
· Allows primitives where boxed primitives are required and vice-versa · Motivating use-case: numbers in collections
// Print a frequency table of words on command line public class Frequency { public static void main(String[] args) { Map m = new TreeMap(); for (String word : args) { Integer freq = m.get(word); m.put(word, (freq == null ? 1 : freq + 1)); } System.out.println(m); } }
44
But Dragons Lurk in These Waters
But Dragons Lurk in These Waters
public class Searching { public static void main(String[] args) { String[] strings = { "0", "1", "2", "3", "4", "5" }; // Translate String array into List of Integer List list = new ArrayList(); for (String s : strings) list.add(Integer.valueOf(s)); System.out.println(Collections.binarySearch(list, 1, cmp)); } // Dangerously broken comparator that usually works fine static Comparator cmp = new Comparator() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i == j ? 0 : 1); } }; }
45
A Surprise Left-Jab While Auto-Unboxing
A Surprise Left-Jab While Auto-Unboxing
public class Parsing { /** * Returns Integer corresponding to s, or null if s is null. * @throws NumberFormatException if s is nonnull and * doesn't represent a valid integer. */ public static Integer parseInt(String s) { return (s == null) ? (Integer) null : Integer.parseInt(s); } public static void main(String[] args) { System.out.println(parseInt("-1")); System.out.println(parseInt(null)); System.out.println(parseInt("1")); } }
46
One Capital Letter Creates Two Billion Unnecessary Objects
One Capital Letter Creates Two Billion Unnecessary Objects
public static void main(String[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }
47
Autoboxing Broke APIs
Autoboxing Broke APIs
· Safe Overloadings Became Unsafe
public class SetList { public static void main(String[] args) { Set set = new LinkedHashSet(); List list = new ArrayList(); for (int i = -3; i < 3; i++) { set.add(i); list.add(i); } for (int i = 0; i < 3; i++) { set.remove(i); // Set.remove(Object) list.remove(i); // List.remove(int) } System.out.println(set + " " + list); } }
48
Autoboxing and Unboxing Critique
Autoboxing and Unboxing Critique
· Reduced the verbosity of using numbers in collections · Distinction between primitives and boxed primitives exists even if you can't see it
Blurring the distinction created a minefield Caused many subtle and serious problems
· Generated more puzzlers than any other JSR-201 change · Conclusion: we should have made generics work for primitives instead
PUKE
49
Varargs
Varargs
· Variable number of arguments in method declarations · Designed primarily for printf and reflection · An example from JavaOne 2004 ("Taming the Tiger")
static int sum(int... args) { int sum = 0; for (int arg : args) sum += arg; return sum; }
· We knew varargs were technically unsafe for use with generics, but didn't think it would be a problem in practice
50
We Were Wrong
We Were Wrong
·Fails Due to Subtle Interaction with Erasure
abstract class Sink { abstract void add(T... elements); void addUnlessNull(T... elements) { for (T element : elements) if (element != null) add(element); } } public class StringSink extends Sink { // Throws NullPointerException private final List list = new ArrayList(); void add(String... elements) { list.addAll(Arrays.asList(elements)); } public String toString() { return list.toString(); } public static void main(String[] args) { Sink ss = new StringSink(); ss.addUnlessNull("null", null); System.out.println(ss); } }
51
Varargs Critique
Varargs Critique
· Very useful, but not very often · Succeeded in enabling printf and improving reflection · Generic array creation warnings are a real nuisance
But this is largely fixed in Java 7
· But still leaky abstraction that interacts poorly with generics · Violates Java "transparency," causing performance issues · Conclusion: a flawed success made worse by generics' shortcomings
PUKE
52
Static Import
Static Import
· Allows unqualified access to static members without extending a type
import static java.lang.Math.*; ... double s = sqrt((1 - cos(theta * PI / 180)) / 2);
· Critique
It does reduce clutter People feared it would be overused, causing bugs and reducing readability
· Thankfully, this didn't happen
PUKE
But it isn't useful all that often
· Does work nicely for enums and certain static utility classes
Conclusion: a very modest success
53
54
54
Strings in switch--Java SE 7
Strings in switch--Java SE 7
· Exactly what you think
static boolean parseResponse(String response) { switch (response.toLowerCase()) { case "y": case "yes": return true; case "n": case "no": return false; } throw new IllegalArgumentException("Invalid response: " + response); }
· Critique
Modest gain in conciseness and (likely) performance Minor moral hazard: may encourage overuse of String Conclusion: modest success
PUKE
55
Binary Literals and Underscores in Numeric Literals
Binary Literals and Underscores in Numeric Literals
· Exactly what you think
int theAnswer = 0b101010; long usNationalDebt = 14_516_500_000_000L; int evenBits = 0b01010101_01010101_01010101_01010101;
· Critique
Binary literals will occasionally be useful Underscores will be well-liked and oft used I know of no compelling use-case for multiple consecutive underscores
· But they do no harm (as far as we know)
Conclusion: modest success
PUKE
56
Multiple Consecutive Underscores Do Encourage Creativity!
Multiple Consecutive Underscores Do Encourage Creativity!
int bond = 0000_____________0000________0000000000000000__000000000000000000+ 00000000_________00000000______000000000000000__0000000000000000000+ 000____000_______000____000_____000_______0000__00______0+ 000______000_____000______000_____________0000___00______0+ 0000______0000___0000______0000___________0000_____0_____0+ 0000______0000___0000______0000__________0000___________0+ 0000______0000___0000______0000_________000+__0000000000+ 0000______0000___0000______0000________0000+ 000______000_____000______000________0000+ 000____000_______000____000_______00000+ 00000000_________00000000_______0000000+ 0000_____________0000________000000007;
57
Multi-Catch
Multi-Catch
· Catch multiple exceptions at once, and deal with them in a unified fashion
static T instantiate(Class extends T> cl) { try { return cl.newInstance(); } catch (IllegalAccessException | InstantiationException e) { throw new IllegalArgumentException(e); } }
PUKE
· Critique
Does what it's supposed to do without undue complication No known downside Conclusion: moderately big win, with high power to weight ratio
58
More Precise Rethrow
More Precise Rethrow
· Allows exception rethrows with no loss of type information
try { methodDeclaredToThrowSeveralCheckedExceptions(); } catch (Exception e) { log(e); throw e; // throws "several checked exceptions," not Exception }
PUKE
· Critique
Does what it's supposed to without undue complication Reduces the need for evil hacks such as sneakyThrow Still have problem of storing exceptions and throwing elsewhere Conclusion: modest win
59
Improved Type Inference for Generic Instance Creation
Improved Type Inference for Generic Instance Creation
· Allows you to omit type arguments to constructors when compiler can infer them
Map> family = new TreeMap<>(); List safeList = Collections.checkedList(new ArrayList<>(), String.class); return new LinkedHashMap<>();
· Critique
It's about time! Many kittens will be saved Complex under the surface, but hidden from programmers Conclusion: big win--high power-to weight ratio
PUKE
60
Try-with-resources (née ARM Block)
Try-with-resources (née ARM Block)
· Automatically closes resources when you exit a block
Linguistic support for the Dispose pattern
· Supports multiple resources without nesting blocks
static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader r = new BufferedReader(new FileReader(path)) { return r.readLine(); } }
PUKE
· Critique
Eliminates lots of verbiage; solves serious resource leak
· Even the JDK got this wrong ~70% of the time
Does not significantly complicate the language
· Even if though it is the biggest language change in Java 7
Conclusion: huge win--very high power-to weight ratio!
61
Simplified Varargs Method
Simplified Varargs Method
· Prior to Java 7, compiler emitted "nuisance warnings" at varargs call sites
If the method is safe, there's no danger to caller
· Warnings now at varargs declaration as well as call site... · But can annotate declaration to suppress call site warnings!
@SafeVarargs public static List asList(T... a) { }
· Critique
A very sensible idea Should eventually eliminate most of the spurious warnings Almost no downside Conclusion: modest success
PUKE
62
Where are the Puzzlers in Java 7?
Where are the Puzzlers in Java 7?
· I don't know · Puzzlers, like corked wine, take time to develop · Joe Darcy and company did a very good job on features
Joe was well aware of the dangers discussed in this talk
http://blogs.oracle.com/darcy/entry/guidance_measure_language_change_size
· So maybe there won't be any puzzlers
But don't bet on it
63
Java Evolution: Past and Present
Java Evolution: Past and Present
· Most early changes were pretty good, but
Better job on inner classes might have obviated the perceived need for lambda Serialization did more harm than good
· Java 5 changes were a mixed blessing
Many useful facilities were added But we vastly underestimated the damage to "the feel of Java"
· Java 7 changes are very promising
We appear to have learned a lesson from Java 5
64
Java Language Evolution: Future
Java Language Evolution: Future
· I'm more worried about Java 8 and subsequent releases · Current Lambda proposal avoids worst excesses of earlier ones
But I believe it's still unnecessarily complex
· Topics being discussed for Java n for n > 8 are scary too
65
Closing Sermon: Please Don't Give Stroustrup the Last Laugh
Closing Sermon: Please Don't Give Stroustrup the Last Laugh
· Considering a new feature? Remember, more is not better · Before adding a feature, demonstrate a genuine need
Typically via statistical analysis of existing code corpora
· Reject these arguments out of hand
Java will die if we don't add [feature] Every other language has [feature] [Some competitive language] has [feature]
· If adding a feature, keep it as simple as possible
Leverage existing language features even if they're not perfect Avoid rocket science Avoid substantial changes to the type system
· Never add a significant feature at the last minute
66
Shameless Plug
Shameless Plug
Signing in Bookstore immediately following talk!
67