1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

27
1 G53SRP: Java Threads Chris Greenhalgh Chris Greenhalgh School of Computer School of Computer Science Science

Transcript of 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

Page 1: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

1

G53SRP: Java Threads

Chris GreenhalghChris Greenhalgh

School of Computer ScienceSchool of Computer Science

Page 2: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

2

Contents• DefinitionDefinition• Motivations Motivations • ThreadsThreads• Java threadsJava threads• Example embedded processExample embedded process• Java Thread API & issuesJava Thread API & issues• ExercisesExercises

• Book: Wellings 1.1 & 2; Burns & Wellings Chapter Book: Wellings 1.1 & 2; Burns & Wellings Chapter 7.1, 7.3.7, 7.3.8 & 7.47.1, 7.3.7, 7.3.8 & 7.4

• See web page for exercisesSee web page for exercises

Page 3: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

3

Definition• Quote: Quote:

– Concurrent programming is the name given to programming Concurrent programming is the name given to programming notation and techniques for expressing potential parallelism notation and techniques for expressing potential parallelism and solving the resulting synchronization and communication and solving the resulting synchronization and communication problems. Implementation of parallelism is a topic in problems. Implementation of parallelism is a topic in computer systems (hardware and software) that is essentially computer systems (hardware and software) that is essentially independent of concurrent programming. Concurrent independent of concurrent programming. Concurrent programming is important because it provides an abstract programming is important because it provides an abstract setting in which to study parallelism without getting bogged setting in which to study parallelism without getting bogged down in the implementation detials.down in the implementation detials.

(Ben-Ari M., 1982, "Principles of Concurrent Programming", (Ben-Ari M., 1982, "Principles of Concurrent Programming", Englewood Cliffs NJ: Prentice Hall).Englewood Cliffs NJ: Prentice Hall).

Page 4: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

4

Why we need it• To fully utilise the processorTo fully utilise the processor

• To express potential parallelism so that To express potential parallelism so that more than one processor can be used to more than one processor can be used to solve the problemsolve the problem

• To model the parallelism in the real worldTo model the parallelism in the real world– Virtually all real-time systems are inherently Virtually all real-time systems are inherently

concurrent — devices operate in parallel in the concurrent — devices operate in parallel in the real worldreal world

Page 5: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

5

T

S

P

A Simple Embedded System

• Overall objective is to keep the temperature and pressure of Overall objective is to keep the temperature and pressure of some chemical process within well-defined limitssome chemical process within well-defined limits

Switch

ADC

ADC

DACScreen

Heater

Thermocouples Pressure Transducer

Pump/Valve

Page 6: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

6

Why we need it• The alternative is to use sequential programming The alternative is to use sequential programming

techniques - techniques - • cyclic execution of a program sequence to handle the various cyclic execution of a program sequence to handle the various

concurrent activitiesconcurrent activities

– complicates the programmer's taskcomplicates the programmer's task

– The resulting programs will be more obscure and The resulting programs will be more obscure and inelegantinelegant

– Decomposition of the problem is more complexDecomposition of the problem is more complex

– Parallel execution much more difficult to achieveParallel execution much more difficult to achieve

– Placement of code to deal with faults is more Placement of code to deal with faults is more problematicproblematic

Page 7: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

7

Elements of concurrent programming

• Expressing: Expressing: – potential concurrencypotential concurrency

• Processes, threads, coroutines, PAR, …Processes, threads, coroutines, PAR, …

– Synchronization/concurrency controlSynchronization/concurrency control• Locks, semaphors, monitors, …Locks, semaphors, monitors, …

– CommunicationCommunication• Shared memory, message passing, RPC, …Shared memory, message passing, RPC, …

Page 8: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

8

Threads• = Virtual processor= Virtual processor

– UNIX processUNIX process– Light-weight thread (e.g. Java)Light-weight thread (e.g. Java)

• SequentialSequential– Execution stateExecution state

• CPU registers (PC, SP, etc.)CPU registers (PC, SP, etc.)• Stack (procedure arguments, local variables)Stack (procedure arguments, local variables)

• Can share memory Can share memory – through object referencesthrough object references

• Scheduled by runtime system/OS (see later notes)Scheduled by runtime system/OS (see later notes)

Page 9: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

9

Processes versus Threads

Operating System

Threads Fibres Process

thread library

Page 10: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

10

Java Concurrency Model (i)• Java supports threadsJava supports threads

– Threads execute within a single JVMThreads execute within a single JVM– Native threadsNative threads map a single Java thread to an map a single Java thread to an

OS threadOS thread– Green threadsGreen threads adopt the thread library approach adopt the thread library approach

(threads are invisible to the OS)(threads are invisible to the OS)– On a multiprocessor system, native threads are On a multiprocessor system, native threads are

required to get true parallelism (but this is still required to get true parallelism (but this is still implementation dependent)implementation dependent)

Page 11: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

11

Java Concurency Model (ii)• Integration with OOP, various models: Integration with OOP, various models:

– asynchronous method callsasynchronous method calls– early return from methodsearly return from methods– futuresfutures– active objectsactive objects

• Java adopts the active object approachJava adopts the active object approach– i.e. an object which can have activity i.e. an object which can have activity

independent of the rest of the applicationindependent of the rest of the application

Page 12: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

12

java.lang.Thread• = JVM-provided Active Object= JVM-provided Active Object

– Each instance is/has one threadEach instance is/has one thread

• Executes the Executes the run()run() method in a new thread when method in a new thread when start()start() is called is called

• Thread ends when Thread ends when run()run() completes (returns) completes (returns)• Concurrent code specified by eitherConcurrent code specified by either

– Subclassing Subclassing Thread Thread and overridingand overriding run() run() or or

– Implementing Implementing java.lang.Runnablejava.lang.Runnable (defining (defining run()run()) and passing to ) and passing to ThreadThread constructor constructor

Page 13: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

13

Threads in Javajava.lang.Thread

void run()void start()...

Thread()Thread(Runnable target)

subclass

association

MyThread

void run(){ ...

}

parameter toMyRunnableObject

void run(){ ...}

implements

java.lang.Runnable(interface)

void run()

© Andy Wellings 2004

Page 14: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

14

Simple Test: what will they print?

• public class Print10 extends Thread {public class Print10 extends Thread { public void run() { // overriden public void run() { // overriden for (int i=0; i<10; i++) { for (int i=0; i<10; i++) { System.out.println(i); System.out.println(i); try { sleep(1000); } try { sleep(1000); } catch (InterruptedException ie) {} catch (InterruptedException ie) {} } } } }}}

• (b)(b)new Print10().run();new Print10().run();new Print10().run(); new Print10().run();

• (a)(a)new Print10().start();new Print10().start();new Print10().start();new Print10().start();

Page 15: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

15

T

S

P

Concurrency Example

• Overall objective is to keep the temperature and pressure of Overall objective is to keep the temperature and pressure of some chemical process within well-defined limitssome chemical process within well-defined limits

Switch

ADC

ADC

DACScreen

Heater

Thermocouples Pressure Transducer

Pump/Valve

Page 16: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

16

Sequential solution (Java pseudo-code)

• while(true) {while(true) { // heater // heater double temp = ReadTemp(); double temp = ReadTemp(); double heat = ConvertT2H(temp); double heat = ConvertT2H(temp); WriteHeater(heat); WriteHeater(heat); WriteScreen(temp); WriteScreen(temp); // value // value double pres = ReadPressure(); double pres = ReadPressure(); double valve = ConvertP2V(pres); double valve = ConvertP2V(pres); WriteValue(valve); WriteValue(valve); WriteScreen(pres); WriteScreen(pres);}}

Page 17: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

17

Sequential solution notes• Temperature and pressure readings are Temperature and pressure readings are

made at the same ratemade at the same rate– Could do ratios of rates if using counters and if Could do ratios of rates if using counters and if

blocks around eachblocks around each

• Delays in reading/setting temperature Delays in reading/setting temperature delays responses to pressure (and vice delays responses to pressure (and vice versa)versa)

• Failure (indefinite postponement) of any Failure (indefinite postponement) of any operation prevents any further actionoperation prevents any further action

Page 18: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

18

Concurrent solution (Thread)(Java pseudo code)

• public class HeaterController extends Thread {public class HeaterController extends Thread { public void run() { public void run() { while(true) { while(true) { double temp = ReadTemp(); double temp = ReadTemp(); double heat = ConvertT2H(temp); double heat = ConvertT2H(temp); WriteHeater(heat); WriteHeater(heat); WriteScreen(temp); WriteScreen(temp); } } } }}}public class ValueController extends Thread {public class ValueController extends Thread { public void run() { public void run() { while(true) { while(true) { double pres = ReadPressure(); double pres = ReadPressure(); double valve = ConvertP2V(pres); double valve = ConvertP2V(pres); WriteValue(valve); WriteValue(valve); WriteScreen(pres); WriteScreen(pres); } } } }}}new HeaterController().start();new HeaterController().start();new ValveController().start();new ValveController().start();

Page 19: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

19

Concurrent solution (Runnable)(Java pseudo code)

• public class HeaterController implements Runnable {public class HeaterController implements Runnable { public void run() { public void run() { while(true) { while(true) { double temp = ReadTemp(); double temp = ReadTemp(); double heat = ConvertT2H(temp); double heat = ConvertT2H(temp); WriteHeater(heat); WriteHeater(heat); WriteScreen(temp); WriteScreen(temp); } } } }}}public class ValueController implements Runnable {public class ValueController implements Runnable { public void run() { public void run() { while(true) { while(true) { double pres = ReadPressure(); double pres = ReadPressure(); double valve = ConvertP2V(pres); double valve = ConvertP2V(pres); WriteValue(valve); WriteValue(valve); WriteScreen(pres); WriteScreen(pres); } } } }}}new Thread(new HeaterController()).start();new Thread(new HeaterController()).start();new Thread(new ValveController()).start();new Thread(new ValveController()).start();

Page 20: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

20

Concurrent solution (anonymous subclass) (Java pseudo code)

• new Thread() {new Thread() { public void run() { public void run() { while(true) { while(true) { double temp = ReadTemp(); double temp = ReadTemp(); double heat = ConvertT2H(temp); double heat = ConvertT2H(temp); WriteHeater(heat); WriteHeater(heat); WriteScreen(temp); WriteScreen(temp); } } } }}.start();}.start();new Thread() {new Thread() { public void run() { public void run() { while(true) { while(true) { double pres = ReadPressure(); double pres = ReadPressure(); double valve = ConvertP2V(pres); double valve = ConvertP2V(pres); WriteValue(valve); WriteValue(valve); WriteScreen(pres); WriteScreen(pres); } } } }}.start();}.start();

Page 21: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

21

Other java thread operations• Thread.sleep(int ms)Thread.sleep(int ms) – calling thread – calling thread

waits for time (at least waits for time (at least msms) to pass) to pass• t.join()t.join()//(int ms)(int ms) – wait for – wait for tt to finish; to finish;

optionally give up waiting after optionally give up waiting after msms• Thread.currentThread()Thread.currentThread() - return - return

reference to thread executing that callreference to thread executing that call• t.interrupt()t.interrupt() – interrupt (next) blocking – interrupt (next) blocking

operation in that thread (see later in course)operation in that thread (see later in course)• t.stop()t.stop() – terminate thread – terminate thread

– deprecated (unsafe) – do not usedeprecated (unsafe) – do not use

Page 22: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

22

Java thread class• class Thread implements Runnable {class Thread implements Runnable {

/* static methods - apply to current thread */ /* static methods - apply to current thread */ public static native Thread public static native Thread currentThreadcurrentThread();();

/* allow another thread to run (non-preemptive) */ /* allow another thread to run (non-preemptive) */ public static native void yield(); public static native void yield();

/* pause thead for at least this long */ /* pause thead for at least this long */ public static native void public static native void sleepsleep(long millis)(long millis) throws InterruptedException; throws InterruptedException;

/* constructors (there are many others) */ /* constructors (there are many others) */ public public ThreadThread();(); public public ThreadThread(Runnable target);(Runnable target);

/* start thread executing */ /* start thread executing */ public synchronized native void public synchronized native void startstart();();

/* over-riden function to execute (else calls run() on target) */ /* over-riden function to execute (else calls run() on target) */ public void public void runrun();();

Page 23: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

23

• /* stop – deprecated *//* stop – deprecated */ public final void public final void stopstop();();

/* started and not yet stopped */ /* started and not yet stopped */ public final native boolean isAlive(); public final native boolean isAlive();

/* interrupt thread, e.g. in wait, sleep *//* interrupt thread, e.g. in wait, sleep */ public void interrupt(); public void interrupt();

/* pause and resume execution – deprecated *//* pause and resume execution – deprecated */ public final void suspend(); public final void suspend(); public final void resume(); public final void resume();

/* properties */ /* properties */ public final void public final void setPrioritysetPriority(int newPriority);(int newPriority); public final int public final int getPrioritygetPriority();(); public final void setName(String name); public final void setName(String name); public final String getName(); public final String getName(); public final ThreadGroup getThreadGroup(); public final ThreadGroup getThreadGroup();

/* Daemon = service thread: application will not wait for a daemon /* Daemon = service thread: application will not wait for a daemon thread to exit */ thread to exit */ public final void public final void setDaemonsetDaemon(boolean on);(boolean on); public final boolean isDaemon(); public final boolean isDaemon();

/* wait for thread to finish */ /* wait for thread to finish */ public final synchronized void public final synchronized void joinjoin(long millis)(long millis) throws InterruptedException; throws InterruptedException;}}

Page 24: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

24

More about Java thread• An application exits when all it has no non-An application exits when all it has no non-

daemon threads alive (see daemon threads alive (see setDaemonsetDaemon). ). • Each thread has a priority which represents Each thread has a priority which represents

its importance or urgency (see its importance or urgency (see setPrioritysetPriority) (more later in the course). ) (more later in the course).

• Java garbage collection is typically Java garbage collection is typically implemented as a low priority thread.implemented as a low priority thread.

• Each Java thread also belongs to a thread Each Java thread also belongs to a thread group. group.

Page 25: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

25

Other Java Thread issues• Preemption/time-slicing of busy threadsPreemption/time-slicing of busy threads

– Not implemented in all JVMsNot implemented in all JVMs– Else requires cooperative multitasking (e.g. Else requires cooperative multitasking (e.g.

calls to calls to Thread.sleep(0)Thread.sleep(0)).).

• Resource RequirementsResource Requirements– Stack (native & Java)Stack (native & Java)

• E.g. ~128MB virtual memory per threadE.g. ~128MB virtual memory per thread

• See See java.niojava.nio for newer non-blocking IO options for newer non-blocking IO options (need fewer threads, e.g. for large web servers)(need fewer threads, e.g. for large web servers)

Page 26: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

26

Summary: Java thread states• Java thread life-cycle:Java thread life-cycle:

– new Thread() sleep(0)new Thread() sleep(0) start() Blocked/ start() Blocked/ [New] [Runnable] [Not Runnable] [New] [Runnable] [Not Runnable] stop() stop() or stop() stop() stop() or stop() run() exits run() exits [Dead] [Dead]

Page 27: 1 G53SRP: Java Threads Chris Greenhalgh School of Computer Science.

27

Summary (ii)• Concurrently executable code expressed as Concurrently executable code expressed as run()run() method of method of RunnableRunnable or or ThreadThread

• Executed concurrently by a Thread object Executed concurrently by a Thread object after after start()start()

• Runs to completion unless Runs to completion unless stop()stop()ed or ed or destroy()destroy()ed (deprecated)ed (deprecated)

• Blocked by Blocked by sleepsleeping, I/O, locking, ing, I/O, locking, waitwait, , joinjoin