concurrent and distributed programmingabujari/pcd1819/lec1.pdf · java continues moving forward jdk...

99
© Armir Bujari [email protected] Universita Degli Studi di Padova Concurrent and Distributed Programming A.A. 2018/2019 Bachelor's Degree in Computer Science

Upload: others

Post on 20-May-2020

14 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

© Armir Bujari – [email protected]

Universita Degli Studi di Padova

Concurrent and Distributed Programming

A.A. 2018/2019Bachelor's Degree in Computer Science

Page 2: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 3: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 4: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 5: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 6: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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.

Page 7: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

77

The Java programming langauge

Page 8: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

88

Java is …

Popular

Page 9: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

99

Java is …

Popularsource: github community

Page 10: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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 …

Page 11: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

1111

Java is good for ...

Big Teams Long-term projects

The key is maintainability.Code readability

Find good developers

High-profile projects

Page 12: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 13: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 14: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 15: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 16: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 17: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

1717

Java Community Process

+

OpenJDK

How Java Evolves

Page 18: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

1818

Java Community Process

Develop standard technical specifications for Java technology

Java Specification Request (JSR) - Changes to make

http://jcp.org/en/procedures/overview

Page 19: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Twitter

and more ...

submit approve

Page 20: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 21: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

21

JDK Development

Changes

Page 22: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 23: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

2323

The story of two JDKs

Page 24: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 25: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 26: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 27: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

2727

Devoxx Belgium 2017 – New release model announced

Page 28: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

28

JDK.${NEXT}

Page 29: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 30: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 31: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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();

Page 32: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

3232

Java 11 / New Launcher Mode

Page 33: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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")

}

}

Page 34: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

34

Longer Term JDK

Futures

Page 35: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 36: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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();}

Page 37: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

}

Page 38: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 39: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 40: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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.

Page 41: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 42: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 43: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

43

Conclusions to

this intro.

Page 44: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 45: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

4545

Evolution Areas of Java

Productivity Performance Modularization

Page 46: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

4646

Rise of Dynamic JVM Languages

And more ...

https://en.wikipedia.org/wiki/List_of_JVM_languages

Page 47: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

47

Source code Java byte code

JVM

Compile

Run

Jython

JRuby

Groovy

Scala

Clojure

...

Page 48: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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/

Page 49: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

© Armir Bujari – [email protected]

Universita Degli Studi di Padova

Concurrent and Distributed Programming

A.A. 2018/2019Bachelor's Degree in Computer Science

Page 50: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 51: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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()

Page 52: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 53: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 54: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

5454

Java Object class Members

• boolean equals(Object obj) • void clone()

• String toString() • void finalize()

• Parameter validation • Builder pattern

In the following

Page 55: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

5555

boolean equals(Object obj)

Page 56: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 57: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 58: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

Page 59: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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!

Page 60: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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);

}

Page 61: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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?

Page 62: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

}

Page 63: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

Page 64: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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…

Page 65: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

Page 66: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)!

Page 67: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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…

Page 68: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 69: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

Page 70: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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?

Page 71: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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(); }

}

Page 72: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 73: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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);}

}

Page 74: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

7474

String toString()

&

void clone ()

Page 75: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 76: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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);

Page 77: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}

Page 78: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 79: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 80: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 81: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 82: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 83: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 84: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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)

Page 85: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 86: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

Page 87: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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;

}}

Page 88: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

8888

Broken – difference based Comparator

Lambda notation:

Comparator<LargeNum> largeNumComparator =

(x, y) x.getNum() – y.getNum();

Integer overflow problems!

Page 89: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

8989

void finalize()

Page 90: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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”

Page 91: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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()

Page 92: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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

}

Page 93: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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.

Page 94: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

9494

Creating and Destroying objects

Page 95: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

9595

Creating and Destroying objects

• Telescoping constructor pattern :

• Hard to write.

• Harder to read :

Page 96: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

9696

Creating and Destroying objects

Page 97: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

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 :

Page 98: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

9898

Creating and Destroying objects

Page 99: Concurrent and Distributed Programmingabujari/pcd1819/lec1.pdf · Java Continues Moving Forward JDK 11 is out –As a LTS Faster Java releases –Feature release every 6 months, LTS

9999

Creating and Destroying objects

• Simulates named optional parameters.

• Consistent state control.

• Builder pattern :

• Easy to write.

• Easy to read :