Docsity

Java Threads & Synchronization: Concepts, Patterns, & Performance, Study notes of Programming Languages

Partial preview of the text

Download Java Threads & Synchronization: Concepts, Patterns, & Performance and more Study notes Programming Languages in PDF only on Docsity!

CMSC 433 – Programming Language

Technologies and Paradigms

Spring 2006

Threads and Synchronization

(thanks to Doug Lea for some slides)

2

Overview

• What are threads?

  • Concept
  • Basic Java mechanisms

• Thread concerns

  • Safety and Liveness
  • Use of synchronization and signaling

• Threading design patterns

3

Computation Abstractions

CPU 1 CPU 2

p1 p2 p3 p t t t t t t t t

A computer

Processes (e.g., JVM’s) Threads 4

Processes vs. Threads

int x; foo() { …x… } int x; foo() { …x… } int x; foo() { …x… } foo() { …x… }

Processes do not

share data

Threads share data

within a process

7

Why Not Multiple Threads?

• Complexity:

  • Dealing with safety, liveness, composition
  • The root of the problem is shared state

• Overhead

  • Higher resource usage
  • May limit asychrony compared to direct event

processing

  • often a low limit on # of allowed threads 8

Programming Threads

• Threads are available in many languages

  • C, C++, Objective Caml, Java, SmallTalk …

• In many languages (e.g., C and C++),

threads are a platform specific add-on

  • Not part of the language specification

• Part of the Java language specification

9

Java Threads

• Every application has at least one thread

  • The “main” thread, started by the JVM to run

the application’s main() method

• The code executed by main() can create

other threads

  • Explicitly, using the Thread class
  • Implicitly, by calling libraries that create

threads as a consequence

  • RMI, AWT/Swing, Applets, etc. 10

Java Threads: Creation

• To explicitly create a thread

  • Instantiate a Thread object
    • An object of class Thread or a subclass of Thread
  • Invoke the object’s start() method
    • This will start executing the Thread ’s run() method concurrently with the current thread
  • Thread terminates when its run() method

returns

13

Example: Synchronous alarms

while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); // sets timeout // wait (in secs) try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } 14

Making It Threaded (1)

public class AlarmThread extends Thread { private String msg = null; private int timeout = 0; public AlarmThread(String msg, int time) { this.msg = msg; this.timeout = time; } public void run() { try { Thread.sleep(timeout * 1000); } catch (InterruptedException e) { } System.out.println("("+timeout+") "+msg); } }

15

Making It Threaded (2)

while (true) { System.out.print("Alarm> "); // read user input String line = b.readLine(); parseInput(line); if (m != null) { // start alarm thread Thread t = new AlarmThread(m,tm); t.start(); } } 16

Alternative: The Runnable Interface

  • Extending Thread prohibits a different parent
  • Instead implement Runnable
    • Declares that the class has a void run() method
  • Construct a Thread from the Runnable
    • Constructor Thread(Runnable target)
    • Constructor Thread(Runnable target, String name)

19

Notes: Passing Parameters

• run() doesn’t take parameters

• We “pass parameters” to the new thread by

storing them as private fields

  • In the extended class
  • Or the Runnable object
  • Example: the time to wait and the message to

print in the AlarmThread class

20

Thread Scheduling

• Once a new thread is created, how does it

interact with existing threads?

• This is a question of scheduling:

  • Given N processors and M threads, which

thread(s) should be run at any given time?

21

Thread Scheduling

• OS schedules a single-threaded process on a

single processor

• Multithreaded process scheduling:

  • One thread per processor
    • Effectively splits a process across CPU’s
    • Exploits hardware-level concurrency
  • Many threads per processor
    • Need to share CPU in slices of time 22

Scheduling Example (1)

CPU 1

CPU 2

p p p p

One process per CPU

p2 threads: (^) p1 threads:

25

Thread Scheduling

  • When multiple threads share a CPU, must decide:
    • When the current thread should stop running
    • What thread to run next
  • A thread can voluntarily yield() the CPU
    • Call to yield may be ignored; don’t depend on it
  • Preemptive schedulers can de-schedule the current

thread at any time

  • Not all JVMs use preemptive scheduling, so a thread stuck in a loop may never yield by itself. Therefore, put yield() into loops
  • Threads are de-scheduled whenever they block

(e.g., on a lock or on I/O) or go to sleep

26

Thread Lifecycle

• While a thread executes, it goes through a

number of different phases

  • New : created but not yet started
  • Runnable : is running, or can run on a free CPU
  • Blocked : waiting for I/O or on a lock
  • Sleeping : paused for a user-specified interval
  • Terminated : completed

27

Which Thread to Run Next?

  • The scheduler looks at all of the runnable threads,

including threads that were unblocked because

  • A lock was released
  • I/O became available
  • They finished sleeping, etc.
  • Of these threads, it considers the thread’s priority.

This can be set with setPriority(). Higher priority

threads get preference.

  • Oftentimes, threads waiting for I/O are also preferred 28

Simple Thread Methods

• void start()

• boolean isAlive()

• void setPriority(int newPriority)

  • Thread scheduler might respect priority

• void join() throws InterruptedException

  • Waits for a thread to die/finish

31

Daemon Threads

• void setDaemon(boolean on)

  • Marks thread as a daemon thread
  • Must be set before thread started

• By default, thread acquires status of thread

that spawned it

• Program execution terminates when no

threads running except daemons