Concurrency in Java: Understanding Threading and Synchronization - Prof. Travis Doom, Study notes of Computer Science

An overview of concurrency in java, focusing on multitasking with multiple programs communicating with each other, implementing the runnable interface, and thread swapping. It also covers possible thread states and concurrency issues, with examples of thread races and synchronization. Students of cs 241 at wright state university, under the guidance of dr. T. Doom, can use this document as study notes, summaries, or cheat sheets to better understand the concepts of concurrency and threading in java.

Typology: Study notes

Pre 2010

Uploaded on 08/18/2009

koofers-user-bmi-1
koofers-user-bmi-1 🇺🇸

10 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
ConcurrencyConcurrency
Multi
p
rocessin
g
pg
Threads/Lightweight objects
Thread methods
Concurrency Issues
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Concurrency in Java: Understanding Threading and Synchronization - Prof. Travis Doom and more Study notes Computer Science in PDF only on Docsity!

ConcurrencyConcurrency^ Multiprocessing

p^

g

Threads/Lightweight objectsThread methodsConcurrency Issues

What is program “execution”?What is program “execution”?

z^ In order to run, a program must be

loaded

into memory and given an

initial^ state

–^ Code space, static variables, heap, stack (with main pushed on)–^ This is a

process, job,

or^ task.

z^ The

Operating System

allows multiple programs/processes to run

z^ The

Operating

System

allows^

multiple programs/processes to run

simultaneously! How?!?–^ multi-tasking (multi-processing) z How can we take advantage of this in our applications?z How^ can we take advantage of this in our applications?–^ Consider Event-driven programming, for starters… z Most corporations have several departments (say management,

i^

f^ i^

d^ l^ )

accounting, manufacturing, and sales).–^ For efficiency, each of these operations should be able to work ontheir tasks on their own, interacting only as necessary

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

–^ Multitasking

with multiple programs

communicating

with each other

Making Threads in JavaMaking Threads in Java

z^ Threads are built into Java (in java.lang.Thread) – no imports necessary! z^ There are two ways to make classes run in separate threads in Java

y^

p

–^ (1) Extend the

Thread

class [includes abstract method:

run ()]

z^ Provides direct access to thread methods, but no other inheritance.– (2) Implement the

Runnable

interface [defines interface method:

run ()]

(2) Implement the

Runnable

interface [defines interface method:

run ()]

z^ Most common mechanism

z^ A new thread can only be created by someone/somewhere calling^ –^

(1) new subThread();

//subThread is a subclass of Thread

-^ (2) new Thread(myRunnable); // myRunnable’s class implements Runnablepublic class MyRunnable implements Runnable {public void run() {doStuff();} // end method run… MyRunnable myRunnable = new MyRunnable();Thread t = new Thread(myRunnable); // define the method on the stackt.start();

// sets thread runnable, and

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

t.start();

// sets thread runnable, and

…^

// pushes run() on stack

Example: Thread RaceExample: Thread Race

public^ class

Threadrace

… public^ void^ go^

()^ {

JFrame^ frame

ne^ JFrame("Thread

Racer")

JFrame^ frame

=^ new^ JFrame("Thread

Racer");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize

frame.setVisible

(true); frame.setLayout

(new^ GridLayout(numberOfRacers,1)); int^ numberOfNonRacerThreads

=^ Thread.activeCount();

for^ (int^

i^ =^ 0;^ i <^ numberOfRacers;

i++)^ {

Racer^ racer

=^ new^ Racer("Racer

"^ +^ i);

frame.add(racer); Thread^ thread

=^ new^ Thread(racer

thread.start

} … } //^ end^ method

go }^ //^ end class^ ThreadRace public^ class

Main^ { public^ static

void^ main

(String[]

args)^ {

ThreadRace

theRace =^ new^ ThreadRace(3); theRace.go();} //^ end^ method

main

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

}^ // } //^ end^ class

main

Example: Thread RaceExample: Thread Race

import^ java.awt.;import^ javax.swing.;public^ class

Racer^ extends

JPanel implements^ Runnable

public { void^ paintComponent

(Graphics

g)^ {

g.setColor

(Color.BLACK);

set^ background

g.fillRect

(0,0,getWidth(),getHeight

g setColor

(Color^

BLUE)^

//^ dra^

line

implements

Runnable

private^ String^ myName; private^ int^ myPosition

=^ 0;

private^ final^ int

numberofSteps

=^ 600;

private^ final^ int

racerHeight

=^ 20;

private^ final^ int

racerWidth

=^ 10;

g.setColor

(Color.BLUE);

//^ draw^ line

g.drawLine

(0,getHeight()/2,getWidth(),getHeight

g.^ setColor

(Color.RED);

//^ draw^

racer

g.fillRect

(myPosition*getWidth()/numberofSteps),

private^ final^ int

racerWidth

private^ int^ speed

=^ 1;

public^ Racer

(String name)^ { myName^ = new^ String

(name); }^ //^ end constructor

Racer

(myPosition

getWidth()/numberofSteps), (getHeight

()^ -^ racerHeight)/2, racerWidth,

racerHeight); }^ //^ end method^ paintComponent public^ void

run^ ()^

private^ void^ pause

(int^ millisec)

//for^ (int

i^ =^ 0; //^ i

<^1000000

*^ millisec;

i++)^ {

//^ busy^ wait^ -^ do

nothing //}

while^ (myPosition

+^ racerWidth

<^ numberofSteps

)^ {

myPosition

+=^ speed; repaint^

pause^ (5);} ThreadRace

setWinner

(myName);

//}try^ { Thread.sleep

(millisec); }^ catch^ (Exception

e)^ { e.printStackTrace

ThreadRace.setWinner

(myName); System.out.println

("Racer "^ +^ myName

"^ has^ finished

the^ race");

}^ //^ end method^ run }^ //^ end class^ Racer

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

} } //^ end^ method

pause

}^ //

Thread swappingThread swapping

z^ How does a computer perform threading?–^

It can do multiple things at one time (if multi-processor)

p^

g^

(^

p^

–^ It can

appear

to do multiple things at one time

z^ The computer has a clock that counts down a quantum for eachexecutable process (and thread)executable process (and thread).–^

When process’s quantum expires, it is taking off the CPU^ z^ Its state is saved for later…The^ scheduler

decides which process gets the next quantum of time

–^ The^

scheduler

decides which process gets the next quantum of time

z^ How is this done fairly?

z^ The programmer can have impact on thread processing by setting priority

int getPriority()int^ getPriority()void setPriority(int)

z^ In Java, the thread with the highest priority

always

get the processor

when it is not

blocked

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Execution with threads of unequal priorityExecution with threads of unequal priority public^ void

go^ ()^ { JFrame^ frame

=^ new^ JFrame("Thread

Racer");

frame.setDefaultCloseOperation

(JFrame.EXIT_ON_CLOSE);

_^ _

frame.setSize

frame.setVisible

(true); frame.setLayout

(new^ GridLayout(numberOfRacers,1)); int^ numberOfNonRacerThreads

=^ Thread.activeCount();

f^ (i t^

i^0 i <^ b^

OfR^

i++)^ {

for^ (int^

i^ =^ 0;^ i <^ numberOfRacers;

i++)^ {

Racer^ racer

=^ new^ Racer("Racer

"^ +^ i);

frame.add(racer);Thread^ thread

=^ new^ Thread(racer); thread.setPriority(thread.getPriority

()^ +^ (2i)-4);*

System.out.println(

"Racer^ " +^ i^ +^ " now^ has priority

"^ +

System.out.println(

Racer^

+^ i^ +^ now^ has^ priority

thread.getPriority()

thread.start

} while^ (Thread.activeCount()

^ numberOfNonRacerThreads)

pause(10);} System.out.println("The

Race^ is over!^ " +^ winner

"^ wins!"); }^ //^ end method^ go Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Example: a concern with race conditionsExample: a concern with race conditions public^ class

Main^ { public^ static

void^ main(String[]

args)^ {

public^ static

void^ main(String[]

args)^ {

Thread^ t; CentralBank

bank^ =^ new^ CentralBank(); System.out.printf("Creating

a^ threads

(%d^ active)\n",

Thread.activeCount()

//^ Create

Thread^ One BranchBank

branch =^ new^ BranchBank

("Branch

Alpha",bank);

t^ =^ new^ Thread^ (branch1); t.start();S^

i^ f("^ l h^ !^ (%d^

i^ )^ "^

h^ d^

i^ C^

System.out.printf("Alpha

away!^ (%d

active)\n",

Thread.activeCount());

//^ Create

Thread^ Two BranchBank

branch =^ new^ BranchBank

("Branch

Beta",^ bank);

t^ =^ new^ Thread^ (branch2); t start();t.start();System.out.printf("Beta

away!^ (%d

active)\n",

Thread.activeCount());

}^ //^ end method^ main }^ //^ end class^ Main Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

Concurrency IssuesConcurrency Issues

run:Creating a threads (1 active)

run:Creating a threads (1 active)

Creating a threads (1 active)Alpha away! (2 active)Beta away! (3 active)Branch Beta adds $1.00 to $0.00 New total: $1.00Branch Alpha adds $1.00 to $0.00 New total: $1.00Branch Alpha adds $1.00 to $1.00 New total: $2.00Branch Beta adds $1.00 to $1.00 New total: $2.

Creating a threads (1 active)Alpha away! (2 active)Beta away! (3 active)Branch Alpha adds $1.00 to $0.00 New total: $1.00Branch Beta adds $1.00 to $0.00 New total: $1.00Branch Alpha adds $1.00 to $1.00 New total: $2.00Branch Beta adds $1.00 to $1.00 New total: $2.

Branch Alpha adds $1.00 to $2.00 New total: $3.00Branch Beta adds $1.00 to $2.00 New total: $3.00Branch Alpha adds $1.00 to $3.00 New total: $4.00Branch Beta adds $1.00 to $3.00 New total: $4.00Branch Alpha adds $1.00 to $4.00 New total: $5.00Branch Beta adds $1.00 to $4.00 New total: $5.00Branch Alpha adds $1 00 to $5 00 New total: $6 00

Branch Alpha adds $1.00 to $2.00 New total: $3.00Branch Beta adds $1.00 to $2.00 New total: $3.00Branch Alpha adds $1.00 to $3.00 New total: $4.00Branch Beta adds $1.00 to $3.00 New total: $4.00Branch Beta adds $1.00 to $5.00 New total: $6.00Branch Beta adds $1.00 to $6.00 New total: $7.00Branch Beta adds $1 00 to $7 00 New total: $8 00

Branch Alpha adds $1.00 to $5.00 New total: $6.00Branch Beta adds $1.00 to $5.00 New total: $6.00Branch Alpha adds $1.00 to $6.00 New total: $7.00Branch Beta adds $1.00 to $6.00 New total: $7.00Branch Beta adds $1.00 to $7.00 New total: $8.00Branch Alpha adds $1.00 to $7.00 New total: $8.00Branch Alpha adds $1.00 to $8.00 New total: $9.

Branch Beta adds $1.00 to $7.00 New total: $8.00Branch Beta adds $1.00 to $8.00 New total: $9.00Branch Alpha adds $1.00 to $4.00 New total: $5.00Branch Alpha adds $1.00 to $9.00 New total: $10.00Branch Alpha adds $1.00 to $10.00 New total: $11.00Branch Beta adds $1.00 to $9.00 New total: $10.00Branch Alpha adds $1.00 to $11.00 New total: $12.

p Branch Beta adds $1.00 to $8.00 New total: $9.00Branch Alpha adds $1.00 to $9.00 New total: $10.00Branch Beta adds $1.00 to $10.00 New total: $11.00BUILD SUCCESSFUL (total time: 1 second)

p Branch Beta adds $1.00 to $12.00 New total: $13.00Branch Alpha adds $1.00 to $12.00 New total: $13.00Branch Alpha adds $1.00 to $13.00 New total: $14.

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

SynchronizationSynchronization

z^ What we need is a mechanism to identify operations which should NOT beinterrupted by another thread z^ Such operations/methods are called

atomic

–^ That is, they cannot be “divided” and must be done to completionbefore anyone can start the method

y

z^ In Java, you can designate a method as being atomic by using the keyword^ syncronized

in the method header

z^ How does Mutual Exclusion (Mutex) work?z^ How does Mutual Exclusion (Mutex) work?–^

Java provides a “lock” on each object.– An object becomes locked when a thread calls any of its synchronizedmethods

That thread gets the “key”

methods. That thread gets the

key.

–^ It requires a key to access any synchronized methods of a locked object.–^ The key is returned (and the object unlocked) when the thread executionl^

h^

h^ i^

d^ h d

Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering

CS 241Computer Programming II

leaves the synchronized method.