java: a fast introduction - web.fhnw.ch · misleading: if we try to think about all possible...

44
Java: A fast introduction Carlo U. Nicola, IMVS FHNW With extracts from publications of : Albert Cohen, INRIA Saclay and École Polytechnique and Randal E. Bryant, David O’Hallaron: Introduction to Computer Systems: A Programmer’s perspective”, Prentice Hall, 2003

Upload: ngonhu

Post on 10-Aug-2019

214 views

Category:

Documents


0 download

TRANSCRIPT

Java: A fast introduction

Carlo U. Nicola, IMVS FHNW

With extracts from publications of : Albert Cohen, INRIA Saclay and École Polytechnique

and Randal E. Bryant, David O’Hallaron:

“Introduction to Computer Systems: A Programmer’s perspective”,

Prentice Hall, 2003

MAS HS12 2

Java is syntactically very similar to C: ! Primitive (scalar), array and Object types

! Control flow: if, while, for... ! Functional abstraction: methods

! Modular composition: separate compilation .java→.class,

package But Java is also an object-oriented language:

! Goal: code reuse and modularization (complementary to functions

alone) ! Classes, objects, generic types

! Interfaces, inheritance

The Java programming language

MAS HS12 3

1. Portable: “Write once, run everywhere” Scott McNeally, former

Sun’s CEO

2. Virtual Machine (VM): abstraction of the hardware machine,

stack based interpreter.

3. Sandboxing of applications on a given VM;

4. Productive and safer memory management: concurrent

garbage collector;

5. Strongly typed language: enhance good software engineering

practices

6. Relatively fast thanks to modern Just-in-Time (JIT) compilation

techniques.

Java: Why?

MAS HS12 4

1. Class: A template of a data object with methods that manipulate them. A

class encapsulate both state (member variable) an behaviour (methods).

2. Abstract class: A non instantiable class that might contain fully

implemented methods.

3. Interface: A specification: Methods’ signatures to be fully implemented.

4. Instance: An instantiation of a Class or Interface physically represented in

memory.

5. Method: A set sequence of instructions.

6. Instance Field: A variable associated with a particular instance.

7. Static Field: A variable shared among all instances of a Class.

Java: Keywords

MAS HS12 5

Java: Class

MAS HS12 6

Java: Object

MAS HS12 7

Main purpose: modify or extend the fundamental behavior of a class

without copying the code of the base (a.k.a. super ) class

Java: Inheritance

MAS HS12 8

Java: Interfaces

1. Specify a subset of the methods to be implemented by a class

2. Main purpose: factor out common properties/actions/capacities of classes

Specification

Implementation

MAS HS12 9

Java: Quiz

Question: should a Rectangle class extend a Square class or should a Square class extend a Rectangle class ?

Hint 1: what about the resize(double x, double y) method?

Hint 2: The class Square is not a square: it is a program that represents a

square. As two lawyers in a divorce case are not divorcing each other so the

representatives of two geometric shapes do not share the relationships of

these shapes.

Hint 0: A subclass (subtype) should inherit all the methods of the superclass.

At most it can add functionality.

MAS HS12 10

Java: Quiz answer (1)

Answer: neither! Both should more likely implement a Polygon interface

Alternative: abstract classes with abstract methods (definition deferred

to child classes)

MAS HS12 11

Java: Quiz answer (2)

Answer: neither! Both should more likely implement a Polygon interface

Alternative: abstract classes with abstract methods (definition deferred

to child classes)

MAS HS12 12

Assignment: ! Define a new class TandemBike re-using a maximum of code we already

developed so far.

! Hints:

(a) You should always program against a specification (interface)

(b) You should think about the consequences of inheritance.

Java programming exercise

MAS HS12 13

Static type checking: ! Safer than casts:

! Note: the compiler “erases” generic

types in favour of casts (dynamic type

checking, enforced by Java standard)

Java: Generic (Java ¸ 5)

MAS HS12 14

Further extension is possible through bounded

type parameters: ! Subtyping constraint:

! Supertyping constraint:

Java: Generic (Java ¸ 5)

MAS HS12 15

Array: Default syntax:

Array: Nicer but do not use with Android (performance problems):

Syntactic sugar: Loops over collections (1)

MAS HS12 16

Collection default syntax:

Collection : Nicer but do not use with Android (performance problems):

Syntactic sugar: Loops over collections (2)

MAS HS12 17

Nicer:

Converting an Array into a List:

Syntactic sugar: Automatic (Un) Boxing

MAS HS12 18

Problem: How many words are there in a phrase?

“Die Kunst ist, einmal mehr aufzustehen, als man umgeworfen wird. ”

Total number of words: 10

Word separator(Trennzeichen) : space (Leerzeichen)

Example: Counting words in a phrase

MAS HS12 19

Read the text from the console

Split the text in chunks separated by spaces and store them in tree

structure

Count the leafs of the tree

Example: A possible solution

MAS HS12 20

Example: Read the text from the console

MAS HS12 21

Example: Split the text in chunks

MAS HS12 22

Example: Count the words in the text

MAS HS12 23

Concurrent programming

MAS HS12 24

The clock speed slows

down but the transistors'

density is still growing.

Obvious change: produce

multicore CPU; but that

means that concurrency is

now the technique of choice

for every application.

Why concurrent programming is necessary

MAS HS12 25

We perceive our minds to work sequentially although 90% of our actions work

unconsciously in parallel (trivial example: Breathing, seeing and hearing )

The notion of linear time in the analysis of a computer program is often

misleading: if we try to think about all possible sequences of events in a computer

we run into messy probabilistic paths which are frequently impossible to sort out.

Classical problem classes of concurrent programs:

1. Races: outcome depends on arbitrary scheduling decisions elsewhere in the

system. Example: who gets the last seat on the airplane?

2. Deadlock: improper resource allocation prevents forward progress Example:

traffic gridlock.

3. Lifelock / Starvation / Fairness: external events and/or system scheduling

decisions can prevent sub-task progress. Example: people always jump in front

of you in a line.

Why concurrent programming is hard

MAS HS12 26

One request at a time:

Iterative server

MAS HS12 27

Flaw in iterative server

MAS HS12 28

Correction: concurrent servers

MAS HS12 29

Process: the traditional view

Process = process context + code, data and stack

MAS HS12 30

Threads: a logical view

Threads associated with processes form a pool of peers each competing for

the same shared resources, unlike processes which grows tree like with their

autonomous resources.

MAS HS12 31

Threads and processes have some common points:

Each has its own logical control flow.

Each can run concurrently.

Each is context switched.

But they have many conspicuous differences:

Threads share code and data, processes (typically) do not.

Threads are somewhat less expensive than processes.

Process control (creating and reaping) is twice as expensive as

thread control.

Linux/Pentium III numbers:

~20K cycles to create and reap a process.

~10K cycles to create and reap a thread.

UML diagram:

Threads versus Processes

MAS HS12 32

Scheduling meetings

Alice wants to schedule a meeting with Bob and Colleen

Bob Alice Colleen “When can

you meet me

Friday?”

“When can

you meet me

Friday?”

“11am or 3pm” “9am or 11am”

“Let’s meet at

11am”

“Let’s meet at

11am”

Reserves 11am

for meeting

Reserves 11am

for meeting

Picks meeting

time

MAS HS12 33

Partial ordering of events

Sequential programs give use a total ordering of events:

everything happens in a determined order

Concurrency gives us a partial ordering of events: we know

some things happen before other things, but we do not know the

total order :

– Alice asks to schedule the meeting before Bob replies

– Alice asks to schedule the meeting before Colleen replies

– Bob and Colleen both reply before Alice picks the meeting

time

– Alice picks the meeting time before Bob reserves the time

on his calendar

MAS HS12 34

Race Condition

Bob Alice Colleen “When can we

meet on

Friday?”

“When can we

meet on

Friday?”

“9, 11am or 3pm”

“9am or 11am”

“Let’s meet at

11am”

“Let’s meet at

11am”

Picks meeting

time

Doug

“When can we

meet on

Friday?”

“9, 11am or 3pm”

“Let’s meet at

11am”

Reserves 11am

for Doug

“I’m busy

then…”

MAS HS12 35

Preventing race conditions: locks

Idea: use locks to impose ordering constraints during the execution of a

concurrent program.

In our example: After responding to Alice, Bob reserves all the times in his

response until he hears back (and then frees the other times)

Bob Alice Colleen “When can

we meet on

Friday?”

“When can

we meet on

Friday?”

“9, 11am or 3pm” “9am or 11am”

“Let’s meet

at 11am”

“Let’s meet

at 11am”

Alice picks

meeting time

Doug

“When can

we meet on

Friday?”

“3pm”

“Let’s meet

at 3”

Locks calendar

MAS HS12 36

Bob Alice Colleen

“When can

we meet on

Friday?”

“When can

we meet on

Friday?”

“9, 11am or 3pm”

Doug “When can

we meet on

Friday?”

Locks calendar

for Alice, can’t

respond to Doug

“When can

we meet on

Friday?”

Locks

calendar

for Doug,

can’t

respond to

Alice

Can’t schedule

meeting, no

response from

Bob

Can’t schedule

meeting, no

response from

Colleen

But now a new problem: deadlock!

Deadlocks

MAS HS12 37

Why are threads so hard?

! Too few ordering constraints: race conditions

! Too many ordering constraints: deadlocks

! Hard/impossible to reason modularly

If an object is accessible to multiple threads, need to think about

what any of those threads could do at any time!

! Testing is even more impossible than it is for sequential code

Even if you could test all the inputs, you still don’t know it will work if

the threads run in a different order.

MAS HS12 38

Multi-Threading concepts

Program Threads in Shared Address Space

Multiple concurrent execution contexts of the same program operating over a shared address space (i.e., shared data)

Hardware Thread in Shared Memory

Multiple concurrent execution contexts actively running on the hardware,

cooperating or not, on a single memory space

MAS HS12 39

Hardware

MAS HS12 40

Multi-Threaded architectures: SMT

Simultaneous Multi Threaded

Intel jargon: hyperthreaded .

MAS HS12 41

Multi-Threaded architectures: Cache-coherent

Chip Multi Processor

Intel jargon: Multi core .

MAS HS12 42

Multi-Threaded architectures: Cache-coherent (SMP)

Symmetric Multi Processor (SMP)

Multiple chips interconnected with a bus core .

MAS HS12 43

Multi-Threaded architectures: Cache-coherent (NUMA)

Non Uniform Memory Architecture (NUMA) Processor i

MAS HS12 44

System on chip: Embedded system

Processor

I/O

Memory