If you can't read please download the document
Upload
carol-mcdonald
View
13.136
Download
0
Embed Size (px)
Citation preview
J2SE 5.0, 6.0
Generics
Concurrency, Garbabe Collection
Carol McDonald
Java Technology Architect
Sun Microsystems, Inc.
Speakers Qualifications
Carol cDonald:
Java Architect at Sun Microsystems
Before Sun, worked on software development of:
Application to manage car Loans for Toyota (>10 million loans)
Pharmaceutical Intranet (Roche Switzerland)
Telecom Network Mgmt (Digital France)
X.400 Email Server (IBM Germany)
Agenda
Language Changes
Generics & Metadata
Library API Changes
Concurrency utilities
Garbage Collection
Virtual Machine
Monitoring & Management
Next Release: Mustang
The agenda will cover all aspects of the new J2SE 5 product
- First we'll examine some of the motivations for the design of J2SE 5 and the main themes used
- We will look at the big changes to the Java language, something that has changed little until Tiger. We'll go into the technical details of generics and metadata to help you understand how to get the most from these features
- J2SE 5 has a lot of new library features. We won't go over all of these because of time constraints, but will focus mostly on the new concurrency utilities that greatly simplify writing multi-threaded applications and gove the programmer a wealth of choice on how to do this.
- We'll look at the changes that have been made at the virtual machine level, seeing how the VM is easier to configure to achieve optimal performance and the new monitoring and manageability features for enterprise deployments.
- At the end we'll sum up and provide you with links to places where you can get more detailed information.
J2SE 5.0 Design Themes
Focus on quality, stability, compatibility
Big emphasis on scalability
exploit big heaps, big I/O, big everything
Ease of development
Faster, cheaper, more reliable
The main design themes for J2SE 5 were:
quality, stability and compatability: Java is used extensively in enterprise, mission critical applications. Customers want a product that is rock solid and will run without problems for as long as they need. Since there are a number of fundamental changes in this release we've been very careful to ensure that moving to J2SE 5 is as painless as possible for existing applications. We don't want people to have to do lots of porting to get their applications running.
Java is truly write once, run anywhere and it's important that Java can fully support every typre of environment from desktop to data centre. We've put a lot of effort into ensuring that the desktop is not neglected and applications can be written that fully fit into the native windowing environment and have performance almost as good (if not better) than native applications.
Since Java is so popular for server applications Sun have also put more effort into ensuring that the algorithms used within the VM for things like memory management and threads will scale to the biggest machines that money can buy.
People are always asking for more features in Java and Sun have tried to address as many of those as they can and which make sense. Since compatability and portability are such basic foundations of Java Sun have been very careful to introduce these new features in an evolutionary rather than revolutionary way.
Finally, probably the biggest single motivation for many of the changes in J2SE 5 was the idea of making Java easier to develop. Java is a third generation language and requires good programming skills to use effectively. As you'll see many of the new features are designed to make programming easier and the end result less prone to errors
Java Language Changes
JDK 1.0
Initial language, very popular
JDK1.1
Inner classes, new event model
JDK 1.2, 1.3
No changes at language level
JDK 1.4
Assertions (minor change)
JDK 5.0
Biggest changes to language since release 1.0
Here we see a brief history of the Java language, showing the changes that have been made over time
As we all know Java was launched in 1995 and has become a very popular language for developement of all types of applications.
As with any new language, developers pretty soon found that there were some things that needed to be fine tuned. Java was lucky in that the 1.1 release only introduced relatively minor changes: the ability to create inner classes and the new event model that would scale much better than the old version.
In JDK 1.2 and 1.3 there were no changes to the language; many new classes were added and a lot of work was done on the performance of the VM but the language remained the same.
In JDK1.4 a minor change was made by introducing assertions.
With the launch of JDK 5.0 we're seeing the biggest changes to the Java language since its launch, and we don't just mean in terms of the version number.
2004
2006
J2SE 5
Tiger
Java SE 6
Mustang
2007
Java SE 7
Dolphin
Java SE road map
2008
2003
2002
2005
J2SE 1.4
EOL
J2SE 1.3.1
5.0Java SE 52004/9
1.6.0Java SE 62006/12
1.7.0Java SE 72008
Tiger Is Everywhere
Tiger
1.4.x
Completed downloads
per month
Over262,295,496downloads served!
Tiger Is Everywhere
Pre-installed on> 60 %of new PCs
Tiger Is Everywhere
99.999 %availability
Previous best: 99.98% for 1.4.2
Tiger Is Stable
Tiger Is Fast
Server Benchmark: SPECjbb2000
Unfortunately, there aren't many benchmarks that span back to the beginning of Java.
This one, (named Volano) probably isn't the best as a general purpose benchmark either.
But the improvement is dramatic: 7 times better performance since 1.2.2.
But this doesn't tell the whole story: The Java platform has gotten better, and this benchmark doesn't take advantage of that!
Tiger [Java SE 5] Features Overview
JDK 6 Features Overview
Now let's spend sometime talking abut Java SE 5 Features
Java SE 1.5Language Changes
Let's start then by looking at the new features included at the language level in J2SE 5
Seven Major New Features
Generics
Autoboxing/Unboxing
Enhanced for loop (foreach)
Type-safe enumerations
Varargs
Static import
Metadata
This slide lists the seven new key features in J2SE 5. We'll describe each of these features. For generics and metadata we're going to go into a lot of detail to help you understand all of the issues around using these features correctly and effectively.
Generics
Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability.
As we'll see generics is a rather bad name for this feature since what we're really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
Is there a problem in here?
Vector v = new Vector();v.add(new Integer(4));OtherClass.expurgate(v);
...
static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) if (((String)it.next()).length() == 4) it.remove();}
OK, Lets take a look at Pre Java SE 5.0 code here.
Can anyone tell if there is a problem here.
Is it a compile time problem or a runtime problem?
What problem? => Runtime exception
The Problem (Pre-J2SE 5.0)
Vector v = new Vector();v.add(new Integer(4));OtherClass.expurgate(v);
...
static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) /* ClassCastException */ if (((String)it.next()).length() == 4) it.remove();}
This piece of code illustrates the problem in Java that generics addresses.
A programmer has created a method called expurgate that takes a collection and removes all strings who's length is four characters from it. The method takes a Collection as a parameter and then iterates through all of the elements looking for four character strings. The Collection can hold objects of any type (meaning strictly speaking that it is generic - see the naming problem?) When we extract an element from the collection we need to do an explicit cast to tell the compiler the type of the object we're getting. This is dangerous, as we can see. A different programmer creates a Vector and rather than adding a String, adds an Integer object. This all compiles fine, as Integer is still a sub-class of Object which is the type of the argument for the add method. However, at run time when the code calls expurgate the VM will throw a ClassCastException since the Integer object is not a String or sub-type of String. This is bad because it is a runtime exception. This code could be running in a telco billing application where runtime exceptions mean potentially large loss of revenue.
What we need is a way to tell the compiler, not the VM what type the collection is so that the compiler can check all uses and report an error when the code is compiled, not when it's running.
This is what generics do.
Generics
Problem: Collection element types
Compiler is unable to verify types
Assignment must use the cast operator
This can generate runtime errors (ClassCastException)
Solution:
Tell the compiler what type the collection is
Let the compiler fill in the cast
To restate the problem, the issue is that the compiler cannot check the types of the objects being stored in a collection because it has no way of knowing the type of the object, other than that it will be an Object or sub-type, which all classes by default are. All assignments when using the collections must do an explicit cast and can generate a runtime ClassCastException.The solution is for the programmer to give an explicit typing to a collection (or other class where this is required). By doing that the compiler can now check that all items added to a typed collection are correct. If we try to add an Integer to a String typed collection we will get a compiler error telling us that it is an inappropriate type. We can make the changes and prevent a runtime exception.The implementation of this feature is only in terms of compilation. The compiler is effectively adding the explicit cast for you and ensuring that only the correct type of obejcts are added. This is a key point from the perspective of compatability, which we'll discuss in more detail later.This is guaranteed to succeed from the point of view of eliminating ClassCastExceptions caused by this type of error. The asterisk is there because this will only hold true if all the code of an application is recompiled using the J2SE 5 compiler, so that all references can be checked. Pre 5.0 class files will still run using the new JVM. If you mix old and new class files you could still get a ClassCastException since the compiler will have been unable to check that the type of object being added to a collection is correct.
Using Generic Classes
Instantiate a generic class to create type specific object
Example
Vector x = new Vector();
x.add(new Integer(5)); // Compiler error!
Vector y = new Vector();
In J2SE 5 all the collection classes (as well as many others) have been made generic. Here we look at the same example we had earlier that would have thrown a ClassCastException.
Using generics, when we instantiate the Vector class we also include a type argument to tell the compiler that the Vector is only to be used to hold objects of type String (String is final so it's not possible to use a sub-class).
If we then try and call the add method with an Integer object as a parameter the compiler will know this is wrong and will report an error.
Lets declare another Vector, this time parameterised for Integer objects. If we return the comparison between the two Vectors what will the result be, true or false? The answer is true. The base type of the objects is still the same, they are both Vector and they both share the same class at runtime. The fact that one has been typed to hold Strings and one has been typed to hold Integers does not affect this comparison. This is an important fact to remember as we'll see later when we discuss type erasure.
Wildcards
Method to print contents of any Collection?
Wrong!
Passing a Collection of type String will give a compiler error
void printCollection(Collection c) { for (Object o : c) System.out.println(o);}
Well of course you all know that I wouldn't ask if the answer was yes.
The problem is that A collection with the type argument of Objects is NOT a supertype of all types of collection. If you try to call this method and pass in a collection with type argument String you will get a compiler error due to the type mismatch.
How do we therefore solve this problem?
Invariant sub-typing:
Collection is not a super-class of Collection
Remember earlier when we saw the comparison of the two references? The base types are the same, but parameters do not have inheritance in the same way as concrete classes.
Wildcards
Correct way:
? is the wildcard type
Collection means Collection of unknown
void printCollection(Collection c) { for (Object o : c) System.out.println(o);}
The answer is using what is called a wildcard type argument. This is the question mark that we saw earlier in the syntax definition for type arguments. The wildcard type is equivalent to saying the type is unknown, so Collection is the same as saying a Collection of unknown type. This is also something important to remember as we'll see shortly
Bounded Wildcards
A wildcard can be specified with an upper bound
public void drawAll(List