Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK...
Transcript of Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK...
© Armir Bujari – [email protected]
Universita Degli Studi di Padova
Concurrent and Distributed Programming
A.A. 2018/2019Bachelor's Degree in Computer Science
22
About the course
• Prerequisites
• Should have sustained the Object Oriented Programming (P2) written exam (vote registered!)
• Organized in two modules (2 * 24h)
• Mod#1: The Java language ecosystem; features and libraries
• Mod#2: Primitives for concurrency, libraries and some Distribution
• Schedule: 8.30-10.30, Class 1C150,
• No lecture tomorrow (Firday 5)
• Laboratories
• Each module has 2 laboratory sessions (2*2h), Lab. P140
• Mod#1: 3rd and 5° week of the course
• Mod#2: 7° and mid December
• Hands-on coding sessions, problem solving
33
About the course
• Rely on software tools
• Build automation i.e., gradle
• Versioning i.e., Git
• Reference text books
• Becoming obsolete (~JSE 5.0): S.Crafa, Oggetti, Concorrenza, Distribuzione. Programmare a diversi livelli di astrazione. Editore Esculapio. 2014.
• (New) Java 8 in Action: Lambdas, Streams, and Functional-style Programming, Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft, Manning Pubblication, 2014.
• Effective Java (3rd Edition) by Joshua Bloch, Pearson, ISBN-13: 978-0134685991
• Java language documentation / specification(s)
44
About the course
• Evaluation
• Written exam at the end of lectures (Quiz style)
• Individual excercises at each end module (thought as bonus points)
• Contact: [email protected], room 412 (entry BC)
• subject: [pcd1819]
• Office hours: Wednesday 10-12h
• The webpage
• http://www.math.unipd.it/~abujari/pcd.html
• Password protected access
55
Mod#1 Outline
• The evolution of the Java language, features and java.lang.Object
• OO Features: Interface, Inner Class and usage
• The Inversion of Control (IoC) principle: forms and examples
• Java Generics, Collections and libraries
• Java IO and Exceptions
• Java New IO (NIO) and NIO2
• Java Serialization and libraries
• Lambdas and Java Streams
• Jar hell & The Java module system
66
Course Objectives
•Understand some advanced features of the language
•Usage of the language in production systems
•Mention of design patterns for recurrent problems
•OO principles taken from granted – already studied during P2.
77
The Java programming langauge
88
Java is …
Popular
99
Java is …
Popularsource: github community
1010
• Statically typed
• Nearly everything is an object
• Singly-rooted hierarchy (Object)
• No explicit memory handling(new but no delete)
It's hard to say language X is better than language Y.
Use the right tool.
Java is …
1111
Java is good for ...
Big Teams Long-term projects
The key is maintainability.Code readability
Find good developers
High-profile projects
1212
Java Source
Code (.java)Java Byte Code
(.class)Compile
Java Compiler
JVM
Win *Nix Mac
Java Language
Specification
JVM
Specification
Run
Why it succeeded?
Write Once, Run Anywhere
1313
•
•
•
•
Java's true invention
Load code from remote and execute locally
Core technique behind Java Applet
Java applet boosted Java’s spreading in dot com age
NASA World Wind applet
Java’s Class Loader
1414
Class Loader Subsystem
•Find and load all what is required by the program at RunTime
•A hierarchy of class loaders
• System class loaders: loads Java libraries required by the program (<JAVA_HOME>/jre/lib,
<JAVA_HOME>/jre/lib/ext, $CLASSPATH)
• User-defined (custom): one canextend the hierarchy and definea custom classloader
1515
Java is …
1996 1997 1998 2000 2002 2004 2006 2011
Java SE 7
J2SE 1.2J2SE 1.4
Java SE 6
Slowly (?) evolving
Version change
New Features:
Generics
Autoboxing/Unboxing
Enums
Annotations ...
J2SE 1J2SE 1.1
J2SE 1.3
J2SE 5
Core lang
Java Applet
1616
Java is …
2004 2014
Slowly (?) evolving
2006 2011 2017 2018
Java SE 5.0
Java SE 6
Java SE 7
Java SE 8
Java SE 9
Java SE 10, 11Version change
New Features:
Generics
Autoboxing/Unboxing
Enums
Annotations ...
Project Lambda
JSR 335, JEP 126
Project Nashorn
JSR 223, JEP 174
Data&Time API
JSR 310, JEP 150
Project Jigsaw
JSR 376
jShell
JEP 222
Ahead-of-Time
Compilation JEP 295
Applet Deprecated
1717
Java Community Process
+
OpenJDK
How Java Evolves
1818
Java Community Process
Develop standard technical specifications for Java technology
Java Specification Request (JSR) - Changes to make
http://jcp.org/en/procedures/overview
1919
MemberExecutive Committee
(EC)
Individuals
- Companies
- Organizations
-Major stakeholders
-Representative cross-section of
the Java Community
JSRs
Game of big players
Eclipse Foundation
HP
IBM
Intel Nokia Oracle
Red Hat SAP
and more ...
submit approve
2020
OpenJDK
• Open-source implementation of Java
• SE Reference implementation of JCP JSRs
• Base of other Java SE implementations
• Oracle collaboration with Red Hat, IBM, Apple, and SAP
21
JDK Development
Changes
2222
OpenJDK: New Release Model
A new version of the JDK will be released every six months
– March (JDK 10) and September 25 (JDK 11)
– Already enacted the new release model
OpenJDK development will be more agile
– Previous target was a release every two years
Three and a half years between JDK 8 and JDK 9
Features will be included only when ready
– Targeted for a release when feature complete
– Not targeted at specific release when started
2323
The story of two JDKs
2424
OpenJDK: More Open Source
Oracle will open-source closed-source parts of the JDK
– Flight recorder
– Mission control
The goal is for there to be no functional differencebetween an Oracle binary and a binary built from OpenJDKsource
– Targeted for completion late 2018
2525
New, new scheme. 'Just' proposed
– $FEATURE.$INTERIM.$UPDATE.$EMERG
– FEATURE: Was MAJOR, i.e. 10, 11, etc.
– INTERIM: Was MINOR. Reserved for future use
– UPDATE: Was SECURITY, but with different incrementing rule
– EMERG: Emergency update outside planned schedule
JDK Version Numbering
2626
Availability Of JDK Updates
Oracle is switching to a long term support (LTS) model
LTS release will have 3 years of public updates
– JDK 8 has been classified as an LTS release
It will have updates for more than 3 years
– Next LTS release September, 2018 (Java 11)
Non-LTS releases are "Feature Releases"
– JDK 9 is a feature release
– Public updates only until next feature release
JDK 9 public updates ended in March, 2018
2727
Devoxx Belgium 2017 – New release model announced
28
JDK.${NEXT}
2929
JDK 10 (March 2018)
• JEP 286: Local variable type inferencevar list = new ArrayList<String>(); // infers ArrayList<String>
var stream = list.stream();// infers Stream<String>
• A few small API changes– New replacemethod in java.util.Properties
– New toStringmethod in java.util.concurrent.FutureTask
– Two new methods in java.lang.StackWalker.StackFrame
– Four new methods in java.util.concurrent.locks.StampedLock
3030
JDK 11 (September 25, 2018)
• Long term support release ( 2021)!
• JEP 323: Align local variable syntax for lambda expressions(x, y) -> x.process(y)
(var x, var y) -> x.process(y)
• JEP 318: Epsilon - An Arbitrarily Low-Overhead Garbage Collector
• JEP 320: Removed the Java EE (JAX-WS, JAXB) and CORBA Modules
• JEP 11: jdk.incubator.httpclient (--add-modules)
3131
JDK 11 (September 25, 2018)
HttpClient client =
HttpClient.newHttpClient();
HttpRequest request =
HttpRequest.newBuilder()
.uri(URI.create("http://openjdk.java.net/"))
.build();
client.sendAsync(request, asString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
3232
Java 11 / New Launcher Mode
3333
Java 11 / Unicode 10 and 11
import java.nio.charset.*;
public class Greetings {
public static void main(String... args) {
System.out.print("Have a \uD83C\uDF7A");
System.out.println(" or a \uD83E\uDD64")
}
}
34
Longer Term JDK
Futures
3535
Project Amber
Several Java enhancements proposals among which:
JEP 305 (Better, faster Pattern Matching support)Object obj = …;
String formatted = "unknown";
if (obj instanceof Integer) {
int i = (Integer) obj;
formatted = String.format("int %d", i);
}
else if (obj instanceof Byte) {
byte b = (Byte) obj;
formatted = String.format("byte %d", b);
}
else if (obj instanceof Long) {
long l = (Long) obj;
formatted = String.format("long %d", l);
}
…
Goal is to print: Type value
3636
Project Amber
String formatted;
switch (obj) {
case Integer i: formatted = String.format("int %d", i); break;
case Byte b: formatted = String.format("byte %d", b); break;
case Long l: formatted = String.format("long %d", l); break;
case Double d: formatted = String.format(“double %f", d); break;
case String s: formatted = String.format("String %s", s); break
default: formatted = obj.toString();}
String formatted
= switch (obj) {
case Integer i String.format("int %d", i);
case Byte b String.format("byte %d", b);
case Long l String.format("long %d", l);
case Double d String.format(“double %f", d);
case String s String.format("String %s", s);
default obj.toString();}
3737
Project Amber
interface Shape {}
class Circle implements Shape {
Point center;
double radius;
}
class Square implements Shape {
Point lowerLeft;
double edge;
}
class Rect implements Shape {
Point lowerLeft;
Point upperRight;
}
Shape shape = ...
double area = switch (shape) {
case Circle (var center, var radius)
PI * radius * radius;
case Square (var lowerLeft, var edge)
edge * edge;
case Rect (var lowerLeft,
var upperRight)
…
}
3838
Project Valhalla
Value types in Java
Why do we need them?
Identity leads to pointers
Pointers lead to indirection
Indirection leads to suffering
(of performance)
3939
Project Valhalla
Java has
– Primitives: for performance
– Objects: for encapsulation, polymorphism,
inheritance, OO
Problem is where we want to use primitives
but can't
– ArrayList<int> won't work
– ArrayList<Integer> requires boxing and
unboxing, object creation, heap overhead,
indirection reference
4040
Project Valhalla
JEP 169 goals
– Support user-defined and library-defined abstract data types with
performance profiles similar to Java primitive types.
– Bring the semantics of int and java.lang.Integer closer
together.
– Allow representation of ubiquitous types currently not well supported
on the JVM, including complex numbers, vector values, and tuples.
– Increase shareability of Java data structures.
– Provide clear and explicit semantics for shared read-only array data.
– Enable functional-style computation with pure data, for optimized
parallel computations.
– Increase safety and security and decrease "defensive copying" in
applications which must share structured data across trust boundaries.
4141
Project Panama
Interconnecting JVM and native code
– Native function calls from JVM (C, C++)
– Native data access from JVM or inside JVM heap
– Header file API extraction tools
– Native library management APIs
– Class and method resolution “hooks”
– Native-oriented JIT optimizations
4242
Project Loom
Further work on making concurrent programming simpler
Threads are too heavyweight
– Too much interaction with operating system
Loom will introduce fibres
– JVM level threads (remember green threads?)
– Add continuations to the JVM
– Use the ForkJoinPool scheduler
– Much lighter weight than threads
Less memory
Close to zero overhead for task switching
43
Conclusions to
this intro.
4444
Java Continues Moving Forward
JDK 11 is out
– As a LTS
Faster Java releases
– Feature release every 6 months, LTS every 3 years
– OpenJDK binaries under GPLv2 with CPE license
Lots of ideas to improve Java
– Value types, better JNI, better type inference
– Many smaller things
4545
Evolution Areas of Java
Productivity Performance Modularization
4646
Rise of Dynamic JVM Languages
And more ...
https://en.wikipedia.org/wiki/List_of_JVM_languages
47
Source code Java byte code
JVM
Compile
Run
Jython
JRuby
Groovy
Scala
Clojure
...
4848
the Da Vinci Machine Project
Extend the JVM with first-class architectural support for languages other than Java, especially dynamic languages.
http://openjdk.java.net/projects/mlvm/
© Armir Bujari – [email protected]
Universita Degli Studi di Padova
Concurrent and Distributed Programming
A.A. 2018/2019Bachelor's Degree in Computer Science
5050
Naming Conventions / 1
•Packages
• com.google.inject, org.joda.time.format
•Class and Interface names
• Timer, FutureTask, LinkedHashMap, HttpServlet
•Method and Field names
• Remove(), ensureCapacity(), getCrc()
•Local Variable
• i, xref, houseNumber
•Constant
• MIN_VALUE, NEGATIVE_INFINITY
•Type Parameter
• T, E, K, V, X, T1, T2
5151
Naming Conventions / 2
• Methods that perform some actions
• Verb or verb phrase
• append(), drawImage()
• Methods that return boolean
• Name usually starts with “is”; sometimes “has”
• isDigit(), isProbablePrime(), isEmpty(), isEnabled(), hasSiblings()
• Methods that return nonboolean
• noun, noun phrase, or verb phrase starting with “get”
• size(), hashCode(), getTime()
• “get” form required for Beans; other form often more readable
• “getters” usually have “setters” (unless immutable…)
• Special cases
• type conversion methods use “to”
• toString(), toArray()
• view methods use “as”
• asType(), asList()
• Common static factory names
• valueOf(), of(), getInstance(), newInstance(), getType(), and newType()
5252
Comments for all exposed API Elements
•Precede every exported class, interface, constructor, method, and field description with a doc comment
•Doc. comment should describe CONTRACT between method and its client
•No two members or constructors should have the same summary description
•Every method should have
• @param tag for each parameter
• @return tag (unless return type is void)
• @throws tag for each exception (both checked and unchecked)
5353
A good example
// Good Example
/**
* Returns the element at the specified position in this list
*
* <p>This method is <i>not</i> guaranteed to run in constant time.
In some implementations it may run in time proportional to the
element position.
*
* @param index index of element to return; must be non-negative
* and less than the size of this list
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException if the index is out of the
range
* ({@code index < 0 || index >= this.size()})
*/
E get(int index)
5454
Java Object class Members
• boolean equals(Object obj) • void clone()
• String toString() • void finalize()
• Parameter validation • Builder pattern
In the following
5555
boolean equals(Object obj)
5656
Object::equals(Object obj)
•Obey the general contract when overriding equals()
•Overriding seems simple, but there are many ways to get it wrong.
•Best approach – Avoid! Works if:
• Each instance of a class is unique
• You don’t care if class has logical equality
• The superclass equals is satisfactory
• Class is not public and equals never used
5757
General contract for equals
•Reflexive
• x.equals(x) must be true
•Symmetric
• x.equals(y) iff y.equals(x)
•Transitive
• If x.equals(y) && y.equals(z)
• Then x.equals(z)
•Consistency…
•Null values:
• x.equals(null) is always false
5858
How hard could this be?
•Reflexivity is pretty much automatic
•Symmetry is not:
• Example CaseInsensitiveString
private String s;
// Broken – violates symmetry
@Override public boolean equals (Object o) {
if (o instanceof CaseInsensitiveString)
return s.equalsIgnoreCase(
((CaseInsensitiveString) o).s);
if (o instance of String) // Not Symmetric!
return s.equalsIgnoreCase((String) o);
return false;
}
5959
Why does this violate symmetry?
•Consider this code:
Object x = new CaseInsenstiveString (“abc”);
Object y = “Abc”; // y is a String
if (x.equals(y)) {…} // evaluates true, so execute
if (y.equals(x)) {…} // evaluates false, so don’t…
•Dispatching of equals() calls
• First equals() call to CaseInsensitiveString
• Second equals() call to String
•This is horrible!
6060
Correct Implementation
•Avoid temptation to be “compatible” with the String class:
// CaseInsensitiveString is not a subclass of String!
private String s;
@Override public boolean equals (Object o) {
return (o instanceof CaseInsensitiveString)
&&
(CaseInsensitiveString o).s.
equalsIgnoreCase(s);
}
6161
Symmetry and Transitivity
•Surprisingly difficult – general result about inheritance
•Example:
• A 2D Point class
• State is two integer values x and y
• equals() simply compares x and y values
• An extension to include color
• public class ColorPoint extends Point
• What should equals() do?
6262
Preliminaries: What does equals in Point look like?
public class Point { // routine code
private int x; private int y;
...
@Override public boolean equals(Object o) {
if (!(o instanceof Point))
return false;
Point p = (Point) o;
return p.x == x && p.y == y;
}
}
6363
Choice 1 for equals() in ColorPoint
•Have equals() return true iff the other point is also a ColorPoint:
// Broken – violates symmetry
@Override public boolean equals(Object o) {
if (!(o instanceof ColorPoint))
return false;
ColorPoint cp = (ColorPoint o);
return super.equals(o) &&
cp.color == color;
}
6464
Problem
•Symmetry is broken
•Different results if comparing:ColorPoint cp = new ColorPoint (1, 2, RED);
Point p = new Point (1,2);
// p.equals(cp), cp.equals(p) differ
•Unfortunately, equals() in Point doesn’t know about ColorPoints
• Nor should it…
•So, try a different approach…
6565
Choice 2 for equals() in ColorPoint
•Have equals() ignore color when doing “mixed” comparisons:
// Broken – violates transitivity
@Override public boolean equals(Object o) {
if (!(o instance of Point)) return false;
// If o is a normal Point, be colorblind
if (!o instanceof ColorPoint)
return o.equals(this);
ColorPoint cp = (ColorPoint o);
return super.equals(o) && cp.color == color;
}
6666
Now symmetric, but not transitive!
•Consider the following exampleColorPoint p1 = new ColorPoint(1,2,RED);
Point p2 = new Point(1,2);
ColorPoint p3 = new ColorPoint(1,2,BLUE);
•The following are true:
• p1.equals(p2)
• p2.equals(p3)
•But not p1.equals(p3)!
6767
The real lesson
•There is no way to extend an instantiable class and add an aspect while preserving the equals contract.
• Note that abstract superclass definitions of equals() are fine.
•Wow! Inheritance is hard!
•Solution: Favor composition over inheritance (later on).
•Note: This was not well understood when some Java libraries were built…
6868
How to implement equals()
•Use == to see if argument is a reference to this (optimization)
•Use instanceof to check if argument is of the correct type (properly handles null)
•Cast the argument to the correct type
•Check each “significant” field
•Check reflexivity, symmetry, transitivity
6969
Be sure to maintain Liskov Substitution Principle
•Rumor has it you can use getClass()instead of instanceof
• WRONG!
// Broken – violates Liskov substitution principle
@Override public boolean equals(Object o) {
if (o == null || o.getClass() != getClass)
return false;
Point p = (Point o);
return p.x == x && p.y == y;
}
7070
Client Use of Point Class
• // Initialize UnitCircle to contain Points on unit circle
private static final Set<Point> unitCircle;
static {
unitCircle = new HashSet<Point>();
unitCircle.add(new Point( 1, 0));
unitCircle.add(new Point( 0, 1));
unitCircle.add(new Point(-1, 0));
unitCircle.add(new Point( 0, -1));
}
public static boolean onUnitCircle (Point p) {
return unitCircle.contains(p);
}
Question: Which Point objects should onUnitCircle() handle?
7171
Completion of prior example
•Now consider a different subclass CounterPoint
• Question: What happens to clients of Point?
• Answer: CounterPoint objects behave badly
public class CounterPoint extends Point
private static final AtomicInteger counter =
new AtomicInteger();
public CounterPoint(int x, int y) {
super (x, y);
counter.incrementAndGet();
}
public int numberCreated() { return counter.get(); }
}
7272
What not to do
•…
•Don’t be too clever
•Don’t substitute another type for Object• @Override public boolean equals (MyClass o)
• Wrong, but @Override tag guarantees compiler will catch problem
• Overloads equals() – does not override it!
• If you choose to override equals, must override hashCode()(later on)
7373
Proper implementation of equals
public class ColorPoint {private Point point;private Color color;
public ColorPoint(...) {...}
public Point asPoint() {return new Point(point.getX(), point.getY());
}
@Overridepublic boolean equals(Object obj) {
if(this == obj) return true;if(!(obj instanceof ColorPoint)) return false;ColorPoint cp = (ColorPoint)obj;return cp.point.equals(point) &&
cp.color.equals(color);}
}
7474
String toString()
&
void clone ()
7575
Object::toString()
•Always override toString()
•Return all the “interesting” information in an object
• PhoneNumber@asde23 vs. +39 049 - 827 1312
•Document intentions with respect to format
• Clients may (unwisely) decide to depend on format
• Provide getters for values toString() provides
Do not force clients to parse String representation
7676
Q&A
Which is more efficient in the long run?
Q1)
final String myName = new String(“Armir”);
vs
final String otherName = “Armir”;
Q2)
String concat = “”;
for(String name: persons) concat+=name;
vs
StringBuilder concat = new StringBuilder(“”);
for(String name: persons) concat.append(name);
7777
Q&A
Is this code efficient for the intended purpose?
private static long sum() {
Long sum = 0L;
for(long i=0; i < Integer.MAX_VALUE; i++) {
sum+=i;
}
return sum;
}
7878
Object::clone()
•Override clone() judiciously
• If so, should implement Cloneable otherwise CloneNotSupportedException is thrown
•Cloneable is a marker interface
• it fails to provide any methods
• clone() is defined in Object (protected)
•Contract:
• Create a copy such that x.clone() != x
• x.clone().getClass() == x.getClass()
• Should have x.clone().equals(x)
• No constructors are called
7979
What a strange contract
•The requirement on classing is too weak
• A lot of extra-linguistic tricks are involved (native code)
No constructor is called
• The only way to do it properly is to call super.clone()
all the way up to Object.
• Explicit use of constructors gives the wrong class.
•Rule: Always/ (if) implement clone() by calling super.clone().
•Coding example
8080
The role of mutability
•If a class has only primitive fields or immutable references as fields, super.clone() returns exactly what you want
•For objects with mutable references, “deep copies” are required.
•Example: cloning a Stack class that uses a reference to an array, collection for a representation.
• Representation must also be cloned .
• So, call super.clone(), then clone the array,
collection
8181
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
this.elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}}
Clone – deepCopy of mutable state
8282
public class Stack implements Cloneable {
…
@Override public Stack clone() {
try {
Stack result = (Stack)super.clone();
result.elements = elements.clone();
}catch(CloneNotSupportedException cnsex) {
throw new AssertionError();
}
return results;
}
}
Clone – deepCopy of mutable state
8383
Other Cloning problems
•Cloning may be a problem with final fields
•Cloning recursively may not be sufficient
•Result:
• You may be better off not implementing Cloneable
• Providing a separate copy mechanism may be
preferable.
• Copy Constructor: public Yum (Yum yum)
• Factory: public static Yum newInstance(Yum yum)
8484
java.lang.Comparable
•Consider Implementing Comparable (not included in Object class)
•Contract
• Returns negative, zero, or positive depending on order of this and specified object
• exp(x.compareTo(y) == -sgn(y.compareTo(x))
• compareTo() must be transitive
• If x.compareTo(y) == 0, x and y must consistently compare to all values z.
• Recommended that x.compareTo(y) == 0 iffx.equals(y)
• Note that compareTo() can throw exceptions (NullPointer, ClassCast)
8585
Elements of the contract
•The same issue with equals() arises in the case of inheritance:
• There is simply no way to extend an instantiable class with a new aspect while preserving the compareTo() contract.
• Same workaround – Favor composition over inheritance
•Some Java classes violate the consistency requirement with equals().
• Example: The BigDecimal class
8686
BigDecimal Example
//This is horrible!
Object x = new BigDecimal(“1.0”);
Object y = new BigDecimal(“1.00”);
// !x.equals(y), but x.compareTo(y) == 0
Set s = new HashSet(); Set t = new TreeSet();
s.add(x); s.add(y);
// HashSet uses equals, so s has 2 elements
t.add(x); t.add(y);
// TreeSet uses compareTo, so t has 1 element
8787
PhoneNumber example
public class PhoneNumber implements Comparable {
private short areaCode;private short prefix;private short lineNum;
@Overridepublic int compareTo(Object obj) {
if(this == obj) return 0;if(!(obj instanceof PhoneNumber))
throw new ClassCastException();
PhoneNumber other = (PhoneNumber)obj;int result = Short.compare(areaCode, other.areaCode);if(result == 0) {
result = Short.compare(prefix, other.prefix);if(result == 0) {
result = Short.compare(lineNum, other.lineNum);}
}return result;
}}
8888
Broken – difference based Comparator
Lambda notation:
Comparator<LargeNum> largeNumComparator =
(x, y) x.getNum() – y.getNum();
Integer overflow problems!
8989
void finalize()
9090
Object::finalize()
•finalize() is a method in the Object class
• What the garbage collector may call when cleaning up an
unused object
•Finalizers: unpredictable, dangerous, unnecessary!
• They are NOT the analog of C++ destructors
•There is no guarantee a finalizer will ever be called
•Finalizers have severe performance penalties
•Instead, provide explicit termination methods
• Sometimes requires “finalizer chaining”
9191
What does this program print?
class Test {
public void finalize() {
System.out.println("finalize()");
};
public static void main (String args[]) {
for(int i=0; ;i++) {
new Prova();
System.out.println(i);
}
}
}
A bad definition of finalize()
92
Code Example
// try-finally block guarantees execution of termination
// method termination method ensures resources are released
// Example resources: database connections, threads, windows
Foo foo = new Foo();
try {
// Do what must be done with foo
} finally {
foo.terminate(); // Explicit termination m() in Foo
}
9393
Creating and Destroying objects
•Consider using the Builder Pattern when faced with many parameters
• Static factories and constructors share a limitation: they
don’t scale well to large members of optional parameters.public class AWithManyParameters {
public AWithManyParameters(int a, int b, long c,
long f….)
}
• Traditionally, two patterns are used :
• Telescoping constructor pattern.
• JavaBeans pattern.
9494
Creating and Destroying objects
9595
Creating and Destroying objects
• Telescoping constructor pattern :
• Hard to write.
• Harder to read :
9696
Creating and Destroying objects
9797
Creating and Destroying objects
• But JavaBean may be in an inconsistent state
partway through its construction !
• JavaBeans pattern :
• Easier to write.
• Easier to read :
9898
Creating and Destroying objects
9999
Creating and Destroying objects
• Simulates named optional parameters.
• Consistent state control.
• Builder pattern :
• Easy to write.
• Easy to read :