COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/]

Similar documents
Chapter 19 Multithreading

Chapter 32 Multithreading and Parallel Programming

Introduction to Java Threads

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Module - 4 Multi-Threaded Programming

Buch gefunden? Im Blackboard eingetragen? Abgabe 1. Übung: , 23:59

Single processor CPU. Memory I/O

CPIT 305 Advanced Programming Multithreading

CSCD 330 Network Programming

CSCD 330 Network Programming

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Chapter 8 Threads Zindell Technologies, Ltd. Question 1: Which one statement below is true concerning the following code?

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

CMSC 132: Object-Oriented Programming II. Threads in Java

CMSC 433 Programming Language Technologies and Paradigms. Spring 2013

Synchronized Methods of Old Versions of Java

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Animation Part 2: MoveableShape interface & Multithreading

Java Threads. COMP 585 Noteset #2 1

Java Threads. Written by John Bell for CS 342, Spring 2018

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Multithread Computing

7. MULTITHREDED PROGRAMMING

Monitors CSCI 201 Principles of Software Development

CSE332: Data Abstractions Lecture 22: Shared-Memory Concurrency and Mutual Exclusion. Tyler Robison Summer 2010

CS11 Java. Fall Lecture 7

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

JAVA EXAMPLES - SOLVING DEADLOCK

Programming Java. Multithreaded Programming

Object Oriented Programming (II-Year CSE II-Sem-R09)

Synchronization

re-exam Concurrent Programming tda383/dit390 Date: Time: 14:00 18:00 Place: Maskinhuset (M)

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Contents. 6-1 Copyright (c) N. Afshartous

CS18000: Programming I

Programming Language Concepts: Lecture 13

Multithreaded Programming

Unit 5 - Exception Handling & Multithreaded

Handouts. 1 Handout for today! Recap. Homework #2 feedback. Last Time. What did you think? HW3a: ThreadBank. Today. Small assignment.

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

CMSC 330: Organization of Programming Languages

Threads Chate Patanothai

Part IV Other Systems: I Java Threads

CS 159: Parallel Processing

CMSC 330: Organization of Programming Languages

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Threads and Java Memory Model

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

More Shared Memory Programming

Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit

CMSC 433 Programming Language Technologies and Paradigms Fall Locks & Conditions

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

Global variables and resources are shared between threads within the same process. Each thread has its own stack and program counter (see Fig 2-7).

CS5233 Components Models and Engineering

CS193k, Stanford Handout #8. Threads 3

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

Java Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

CMSC 433 Programming Language Technologies and Paradigms. Composing Objects

Unit - IV Multi-Threading

Synchronization in Concurrent Programming. Amit Gupta

CISC 4700 L01 Network & Client-Server Programming Spring Cowell Chapter 15: Writing Threaded Applications

Programming Language Concepts: Lecture 11

Problems with Concurrency. February 19, 2014

Principles of Software Construction: Concurrency, Part 2

JFokus Finding And Solving Java Deadlocks

Lecture 9: Introduction to Monitors

Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Multithreading. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

CSE 332: Data Structures & Parallelism Lecture 17: Shared-Memory Concurrency & Mutual Exclusion. Ruth Anderson Winter 2019

Program #3 - Airport Simulation

Threads and Concurrency in Java

Parallel Code Smells: A Top 10 List

Synchronization synchronization.

Threads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015

Advanced Concepts of Programming

Only one thread can own a specific monitor

Threads Questions Important Questions

Info 408 Distributed Applications Programming Exercise sheet nb. 4

Multi-threading in Java. Jeff HUANG

CSCI-1200 Data Structures Fall 2009 Lecture 25 Concurrency & Asynchronous Computing

Computation Abstractions. CMSC 330: Organization of Programming Languages. So, What Is a Thread? Processes vs. Threads. A computer.

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Thread Programming. Comp-303 : Programming Techniques Lecture 11. Alexandre Denault Computer Science McGill University Winter 2004


Component-Based Software Engineering

Concurrency. Fundamentals of Computer Science

Michele Van Dyne MUS 204B Concurrency Issues

Synchronization I. Jo, Heeseung

Java Threads. Introduction to Java Threads

1) Discuss the mutual exclusion mechanism that you choose as implemented in the chosen language and the associated basic syntax

COMP346 Winter Tutorial 4 Synchronization Semaphores

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

ECE 462 Exam 3. 11:30AM-12:20PM, November 17, 2010

CMSC 132: Object-Oriented Programming II

Teaching predicates and invariants on shared data structures in concurrent programming

Transcription:

COMPSCI 230 Threading Week8 Figure 1 Thread status diagram [http://www.programcreek.com/2009/03/thread-status/] Synchronization Lock DeadLock Why do we need Synchronization in Java? If your code is executing in multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable

Q1, Look at the AccountWithoutSync.java, the customer wants to create 100 threads, and using each thread to add one penny. After 100 threads, the balance should equal to 100. package Q1; public class AccountWithoutSync { private Account account = new Account(); private Thread[] thread = new Thread[100]; public static void main(string[] args) { AccountWithoutSync test = new AccountWithoutSync(); System.out.println("What is balance? " + test.account.getbalance()); public AccountWithoutSync(){ ThreadGroup g = new ThreadGroup("group"); boolean done = false; for(int i =0 ; i< 100; i++) { thread[i] = new Thread(g,new AddAPennyThread(), "t"); thread[i].start(); while (!done) if(g.activecount() == 0) done = true; // An inner class of task for adding a penny to the account class AddAPennyThread extends Thread { public void run() { account.deposit(1); class Account { private int balance = 0; public int getbalance() { return balance; public void deposit(int amount) { int newbalance = balance + amount; Thread.sleep(5); catch (InterruptedException ex) { // do nothing balance = newbalance;

Q1-a: When you run AccountWithoutSync.java, what s the balance? 3 Q1-b: what s the problem? The object is shared among multiple threads, which has been corrupted by different threads. Q1-c: How to fix this problem? Public synchronized void deposit(int amount) Cooperation Among Threads Use the wait(), notify(), and notifyall() methods to facilitate communication among threads. The wait(), notify(), and notifyall() methods must be called in a synchronized method or a synchronized block on the calling object of these methods. Otherwise, an IllegalMonitorStateException would occur. The wait() method lets the thread wait until some condition occurs. When it occurs, you can use the notify() or notifyall() methods to notify the waiting threads to resume normal

execution. The notifyall() method wakes up all waiting threads, while notify() picks up only one thread from a waiting queue. Thread 1 Thread 2 synchronized (anobject) { // Wait for the condition to become true while (!condition) anobject.wait(); // Do something when condition is true catch (InterruptedException ex) { ex.printstacktrace(); Resume synchronized (anobject) { // When condition becomes true anobject.notify(); or anobject.notifyall();...

Q2: Try to finish ThreadCooperation.java. Write a program that demonstrates thread cooperation. Suppose that you create and launch two threads, one deposits to an account, and the other withdraws from the same account. The second thread has to wait if the amount to be withdrawn is more than the current balance in the account. Whenever new fund is deposited to the account, the first thread notifies the second thread to resume. If the amount is still not enough for a withdrawal, the second thread has to continue to wait for more fund in the account. Assume the initial balance is 0 and the amount to deposit and to withdraw is randomly generated. Q2-a : Implement code in Deposit() function, if the current balance is more than the withdraw amount, then the current thread will notify another thread to withdraw the money public synchronized void deposit(int amount) { balance += amount; System.out.println("Deposit " + amount + "\t\t\t\t\t" + getbalance()); notifyall(); Q2-b : Implement code in Withdraw() function, if the current balance is less than the withdraw amount, then the current thread will wait another thread to deposit more money? public synchronized void withdraw(int amount) { while (balance < amount) wait(); catch (InterruptedException ex) { ex.printstacktrace(); balance -= amount; System.out.println("\t\t\tWithdraw " + amount + "\t\t" + getbalance());

Q3: Modify the IncreaseNumber method to accept a parameter of type int. Write a recursive algorithm that increases number by 1 on each iteration and prints it to the console then recalls IncreaseNumber with the parameter decreased by 1. The recursion should stop when the counter param == 0. Include the current thread ID in the output. public void IncreaseNumber(int counter){ if(counter ==0){ return; else{ number = number + 1; System.out.println("Thread ID " + Thread.currentThread().getId() + ": " + number); IncreaseNumber(counter - 1); Q3-B: We see conflict between the threads in accessing the variable number. Without using the synchronized keyword. Create a ReentrantLock object and place a lock over the critical section of IncreaseNumber. ReentrantLock lock1 = new ReentrantLock(); //in constructor. lock1.lock(); number = number + 1; System.out.println("Thread ID " + Thread.currentThread().getId() + ": " + number); IncreaseNumber(counter - 1); lock1.unlock(); Q3-C Where is the critical section that is protected by the ReentrantLock? Between the lock() and unlock() calls on the ReentrantLock object. Q3-D: Add a period of sleep to the basecase of the recursion for 10 seconds. if(counter ==0){ Thread.sleep(10000); catch (InterruptedException e) { // TODO Auto-generated catch block e.printstacktrace(); return; else{//.

Q3-E: Change the lock acquisition to timeout after 3 seconds. If it times out, print that thread ID that couldn t obtain the lock. //needs a try/catch block if(lock1.trylock(3l, TimeUnit.SECONDS)){ // critical code here else{ System.out.println("Lock could not be obtained - Timeout: " + Thread.currentThread().getId()); catch (InterruptedException e) { // TODO Auto-generated catch block e.printstacktrace(); Q3-F: Why can a thread continue to recursively call the same method even if it contains the critical section protected by a lock? It is reentrant which means it is allowed to re-acquire the same lock without issue.