Docsity

Java Concurrency: Understanding Race Conditions and Synchronization - Prof. Ana L. Milanov, Study Guides, Projects, Research of Programming Languages

Toggle sidebar
bg1
1
1
Announcements
Project 2 is Graded
Project 3: Python and Java
Due April 28th
I will post test data for Part 1 after class
Practice Problems for Final
Posted one set of problems
Off Announcements page
I will post another set of problems after class
2
Last Class
Method Overloading in Java
Overview of Java Programming Assignment
Intro to Concurrency
Message passing model and shared memory model
Concurrency in Java
Threads
What can go wrong with threads?
Synchronization
3
Concurrency in Java (continue)
4
Topics
Concurrency in Java
Threads
What can go wrong with threads?
Synchronization
Organizing concurrent applications: execution of
tasks
Synchronizers
Latches
5
Threads
Java has explicit support for multiple threads
Two ways to create new threads:
Extend java.lang.Thread
Override “run()” method
Implement Runnable interface
Include a “run()” method in your class
Starting a thread
new MyThread().start();
new Thread(runnable).start();
Abstracted away by Executor framework
6
Terminology
Concurrent programming is about managing shared
mutable state
Shared state – memory locations that can be accessed by
multiple threads
Mutable state – the value of a location could change
during its lifetime
Atomic action – action that executes on the
machine as a single indivisible operation
E.g., fetch the value of iis atomic
E.g., write the value of iis atomic
E.g., i++ is not atomic
pf3
pf4
pf5

Partial preview of the text

Download Java Concurrency: Understanding Race Conditions and Synchronization - Prof. Ana L. Milanov and more Study Guides, Projects, Research Programming Languages in PDF only on Docsity!

1

Announcements

 Project 2 is Graded

 Project 3: Python and Java

 Due April 28

th

 I will post test data for Part 1 after class

 Practice Problems for Final

 Posted one set of problems

 Off Announcements page

 I will post another set of problems after class

2

Last Class

 Method Overloading in Java

 Overview of Java Programming Assignment

 Intro to Concurrency

 Message passing model and shared memory model

 Concurrency in Java

 Threads

 What can go wrong with threads?

 Synchronization

3

Concurrency in Java (continue)

4

Topics

 Concurrency in Java

 Threads

 What can go wrong with threads?

 Synchronization

 Organizing concurrent applications: execution of

tasks

 Synchronizers

 Latches

5

Threads

 Java has explicit support for multiple threads

 Two ways to create new threads:

 Extend java.lang.Thread

 Override “run()” method

 Implement Runnable interface

 Include a “run()” method in your class

 Starting a thread

 new MyThread().start();

 new Thread(runnable).start();

 Abstracted away by Executor framework

6

Terminology

 Concurrent programming is about managing shared

mutable state

 Shared state – memory locations that can be accessed by

multiple threads

 Mutable state – the value of a location could change

during its lifetime

 Atomic action – action that executes on the

machine as a single indivisible operation

 E.g., fetch the value of i is atomic

 E.g., write the value of i is atomic

 E.g., i++ is not atomic

7

What Could Go Wrong?

class Account {

int balance = 0;

void deposit (int x) {

this.balance = this.balance + x;

class AccountTask implements Runnable {

public void run() {

Main.act.deposit(10);

public class Main {

static Account act = new Account();

public static void main(String args[]) {

new Thread(new AccountTask()).start(); // Thread A

new Thread(new AccountTask()).start(); // Thread B

Account object is shared mutable state.

8

What Could Go Wrong? (ii)

Thread A: Thread B:

r1 = act.balance

r1 += 10

act.balance = r1 r2 = act.balance

r2 += 10

act.balance = r

9

A common bug: Race Conditions

 New types of bugs occur in concurrent

programs; race conditions are the most

common

 A data race (a type of race condition) occurs

when two threads can access the same

memory location “simultaneously” and at

least one access is a write

x=1 if (x==0)

Thread A: Thread B:

true-part

10

A common bug: Race Conditions (ii)

 Check-and-act data race

 A common kind of data race

if (instance==null) instance = new …

public class LazyInitRace {

private ExpensiveObject instance = null;

public ExpensiveObject getInstance() {

if (instance == null)

instance = new ExpensiveObject();

return instance;

Thread A: Thread B:

The two callers (in thread A and thread B) will receive different instances although there should be only one instance!

if (instance==null) instance = new …

11

synchronized Block

 To try to avoid race conditions, use

synchronization

 To ensure atomic execution of a block, use

synchronized:

synchronized ( lock ) {

// Read and write of shared state

A reference to an object

12

synchronized Method

 You can also declare a method as synchronized:

synchronized int m(String x) {

// blah blah blah

equivalent to:

int m(String x) {

synchronized (this) {

// blah blah blah

19

Thread Safety

 Concurrent programming is about managing shared

mutable state. Difficult to get right!

 Many things can go wrong when multiple threads

access shared mutable state. Why?

 Exponential number of interleavings of thread operations

 Complex object structure

 Common bugs in concurrent programming

 Race conditions

 Atomicity violations

 To try to avoid these bugs, use synchronization

 Thread safety is difficult to define

 Informally, a class is said to be thread-safe if it behaves

correctly when accessed by multiple threads

20

What Can We Do?

 Analyze shared mutable state very carefully

 Analyze the methods that modify a shared object

and try to see what can go wrong when these

methods interact with other methods

 Note that a data race may happen on a location

which is deeply encapsulated within the “top-

level” shared object

 Use library classes, which are often designed

to be “thread safe”

21

Java Programming Assignment

 There is shared mutable state: seen (the set

of seen puzzle positions)

 Sequential version of solver:

HashSet seen = new HashSet();

if (!seen.contains(p)) {

seen.add(p);

 What can go wrong if we use seen as it is in the

concurrent version of solver?

 You will need to make seen “safe”

22

Java Programming Assignment (ii)

 Implementing seen “safely”:

 Synchronized Collections (since Java 1.2)

 Created by Collections.synchronizedXxx methods

 E.g., Set seen = Collections.synchronizedSet(new HashSet());

 All public methods synchronized by this

 External iteration is problematic

 E.g.,

(for Iterator it = seen.iterator(); it.hasNext();) {

RushHour rh = (RushHour) it.next();

// do something with rh object

 What can go wrong with code on previous slide (assuming

seen is a synchronized set)?

23

Java Programming Assignment (iii)

 Implementing seen “safely”:

 Concurrent Collections (since Java 1.5)

 E.g., ConcurrentHashMap

 Implement different, more efficient (concurrent)

synchronization mechanism

 Provide weak iterators – i.e., iterators that do not

throw ConcurrentModificationException

 Provide additional atomic operations

 E.g., putIfAbsent(key, value)

24

Organizing Concurrent Applications

 One way to organize concurrent programs:

 Organize program into tasks

 Identify tasks and task boundaries

 Tasks should be mostly independent of other tasks

 Ideally, they do not depend on mutable shared state and do

not write mutable shared state

 If there is mutable shared state, should be synchronized

appropriately!

 Each task should be a relatively small portion of the

total work

25

Sequential Task Execution

 A Web Server

 What problems do you see here?

public class SingleThreadedWebServer {

public static void main(String[] args)

throws IOException {

ServerSocket socket = new ServerSocket(80);

while (true) {

Socket connection = socket.accept();

handleRequest(connection);

26

Explicit Threads for Task Execution

public class ThreadPerTaskWebServer {

public static void main(String[] args)

throws IOException {

ServerSocket socket = new ServerSocket(80);

while (true) {

Socket connection = socket.accept();

Runnable task = new Runnable() {

public void run() {

handleRequest(connection);

new Thread(task).start();

27

The Executor Framework

 Part of java.util.concurrent (Java 1.5)

 Flexible thread pool implementation

 High-level abstraction: Executor, not Thread

 Decouples task submission from task execution

 E.g., Executor e managers a thread pool of 3 threads

e.g., Executor e = …^ A^ B^ C e.execute(t1); e.execute(t2); e.execute(t3); e.execute(t4); e.execute(t5); e.execute(t6);

time

t t t t4 t

t

task submission

task execution 28

Using Executor for Task Execution

public class TaskExectorWebServer {

private … Executor e = Excutors.newFixedThreadPool(3);

public static void main(String[] args)

throws IOException {

ServerSocket socket = new ServerSocket(80);

while (true) {

Socket connection = socket.accept();

Runnable task = new Runnable() {

public void run() {

handleRequest(connection);

e.execute(task);

29

Java Programming Assignment

 Identify the tasks

 Possibly best way to concurrent solver

 Use Executor

30

Synchronizers

 A synchronizer is an object that coordinates the

control flow of threads

 When a thread enters synchronizer methods, it either

passes, or it is forced to wait

 A synchronizer has

 State

 Methods that manipulate state

 Mechanisms that cause a thread to wait for the

synchronizer object to reach its terminal state

 Java 1.5 provides several synchronizer classes

 CountDownLatch (a latch), Semaphore (a semaphore),

CyclicBarrier (a barrier)