Synchronization

Similar documents
Threads Questions Important Questions

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

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

Synchronization I. Jo, Heeseung

Agile Development

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

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Hank Levy 412 Sieg Hall

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

COMP31212: Concurrency A Review of Java Concurrency. Giles Reger

10/17/ Gribble, Lazowska, Levy, Zahorjan 2. 10/17/ Gribble, Lazowska, Levy, Zahorjan 4

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

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

Synchronization I. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

CIS233J Java Programming II. Threads

CMSC 132: Object-Oriented Programming II

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

Dealing with Issues for Interprocess Communication

What is a thread anyway?

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

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multi-threading in Java. Jeff HUANG

INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.

Operating Systems. Synchronization

Concurrent Programming using Threads

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

Concurrency Control. Synchronization. Brief Preview of Scheduling. Motivating Example. Motivating Example (Cont d) Interleaved Schedules

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

Threads and Java Memory Model

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

Programming Language Concepts: Lecture 11

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

Java s Implementation of Concurrency, and how to use it in our applications.

Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Le L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading

Administrivia. Events this week Drop-In Resume and Cover Letter Editing Date: Tues., Mar 23 Time: 12:30 2:30 pm Location: Rm 255, ICICS/CS

Concurrent Processes Rab Nawaz Jadoon

COMPSCI 230 Threading Week8. Figure 1 Thread status diagram [

Multithreading Pearson Education, Inc. All rights reserved.

Overview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1

CSCD 330 Network Programming

CSCD 330 Network Programming

Real-Time and Concurrent Programming Lecture 4 (F4): Monitors: synchronized, wait and notify

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Synchronization in Concurrent Programming. Amit Gupta

Race Conditions & Synchronization

Multithreaded Programming

CSE332: Data Abstractions Lecture 19: Mutual Exclusion and Locking

CST242 Concurrency Page 1

ECE 462 Object-Oriented Programming using C++ and Java. Scheduling and Critical Section

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Virtual Machine Design

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

Note: Each loop has 5 iterations in the ThreeLoopTest program.

CS 153 Design of Operating Systems Winter 2016

Concurrency & Synchronization. COMPSCI210 Recitation 25th Feb 2013 Vamsi Thummala Slides adapted from Landon Cox

Process Characteristics. Threads Chapter 4. Process Characteristics. Multithreading vs. Single threading

Threads Chapter 4. Reading: 4.1,4.4, 4.5

Animation Part 2: MoveableShape interface & Multithreading

CS 571 Operating Systems. Midterm Review. Angelos Stavrou, George Mason University

Chapter 3 Process Description and Control

CS 556 Distributed Systems

Multithread Computing

Unit - IV Multi-Threading

Threads and Parallelism in Java

Module - 4 Multi-Threaded Programming

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

7. MULTITHREDED PROGRAMMING

Multiple Inheritance. Computer object can be viewed as

Programming in Java

CMSC 330: Organization of Programming Languages

Unit 5 - Exception Handling & Multithreaded

Programmazione di sistemi multicore

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

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

Problem Set 2. CS347: Operating Systems

1. Introduction to Concurrent Programming

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

Chapter 32 Multithreading and Parallel Programming

Java Threads. COMP 585 Noteset #2 1

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Object Oriented Programming. Week 10 Part 1 Threads

Multitasking. Multitasking allows several activities to occur concurrently on the computer Levels of multitasking: Process based multitasking

Introduction to Java Threads

Writing Parallel Programs COMP360

Performance Throughput Utilization of system resources

COMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION

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

MCS-378 Intraterm Exam 1 Serial #:

UNIT IV MULTITHREADING AND GENERIC PROGRAMMING

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

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

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

Concurrent Programming

CSE 374 Programming Concepts & Tools

MultiThreading. Object Orientated Programming in Java. Benjamin Kenwright

JAVA CONCURRENCY FRAMEWORK. Kaushik Kanetkar

MultiJav: A Distributed Shared Memory System Based on Multiple Java Virtual Machines. MultiJav: Introduction

Synchronization COMPSCI 386

Multithreaded Programming

Transcription:

Synchronization 10-28-2013

Synchronization Coming next: Multithreading in JavaFX (javafx.concurrent) Read: Java Tutorial on concurrency JavaFX Tutorial on concurrency Effective Java, Chapter 9 Project#1: due Wed, October 30 th Exam#2 is scheduled for Tues., Nov. 19, 7:00 pm, Snell 213

What is a thread? process running program thread single, sequential flow of control within a program ( lightweight process) What resources do threads share? What is not shared? the threads share the resources & data in the program each thread has its own stack and program counter

Methods for creating a thread: Implement the Runnable Interface (preferred) Extend the Thread class What are thread states? new, runnable (running), blocked (waiting for a lock), waiting (for another thread), timed_waiting, terminated

Note: the JVM scheduler must coordinate with the Operating System From the pool of runnable threads, choose the one with the highest priority If a tie, use round-robin scheduling Each thread gets a time slice When the time slice expires (or the thread stops running), then run the next one The JVM uses preemptive scheduling If a thread enters the runnable state and it has a higher priority than the currently running thread, then switch them (higher priority thread becomes running, other one returns to runnable)

public class X { // note that class X is not Runnable private Thread t; // composition (X hasa thread) public X( ) { // constructor for class X t = new Thread ( new Runnable() { public void run() { /* code that this thread runs */ } // end run method } // end anonymous Runnable class ); // ends the call to Thread s constructor t.start(); // thread t is now ready to run } // end X constructor

Two concurrent threads must be able to execute correctly with *any* interleaving of their instructions Scheduling is not under the control of the application writer Note: instructions means machine instructions, not a line of code in a high level programming language If two threads are operating on completely independent data or the shared data/resources are read-only, then there s no problem If they share data, then application programmer may need to introduce synchronization primitives to safely coordinate their access to the shared data/resources

Suppose we have multiple threads sharing a database of bank account balances. Consider the deposit and withdraw functions int withdraw (int account, int amount) { balance = readbalance(account); balance = balance amount; updatebalance(account, balance); return balance; } int deposit (int account, int amount) { balance = readbalance(account); balance = balance + amount; updatebalance(account, balance); return balance; } What happens if multiple threads execute these functions for the same account at the same time?

Balance starts at $500 and then two processes withdraw $100 at the same time Two people at different ATMs; Update runs on the same back-end computer at the bank int withdraw(int acct, int amount) { balance = readbalance(acct); balance = balance amount; updatebalance(acct,balance); return balance; } int withdraw(int acct, int amount) { balance = readbalance(acct); balance = balance amount; updatebalance(acct,balance); return balance; } What could go wrong? Different Interleavings => Different Final Balances!!!

If the second does readbalance before the first does writebalance. Two examples: balance = readbalance(account); balance = readbalance(account); balance = balance - amount; updatebalance(account, balance); $500 $500 balance = readbalance(account); balance = readbalance(account); balance = balance - amount; updatebalance(account, balance); balance = balance - amount; updatebalance(account, balance); $400 balance = balance - amount; updatebalance(account, balance); Before you get too happy, deposits can be lost just as easily!

Two concurrent threads must be able to execute correctly with *any* interleaving of their instructions Scheduling is not under the control of the application writer Note: instructions means machine instructions, not a line of code in a high level programming language When the correct output depends on the scheduling or relative timings of operations, you call that a race condition. Output is non-deterministic To prevent this we need mechanisms for controlling access to shared resources, i.e. enforce determinism

Synchronization required for all shared data structures like Shared databases (like account balances) Global variables Dynamically allocated structures (off the heap) like queues, lists, trees, etc. What are not shared data structures? Variables that are local to a procedure/method (on the stack) Note, though, that other bad things happen if try to share pointer to a variable that is local to a procedure

Have an array of accounts (simulating the bank) Have several threads, where each thread transfers some money from 1 randomly chosen account to another Periodically, test to see if the bank still has the same amount of money in the accounts public void transfer(int from, int to, int amount) { if (accounts[from] < amount) return; accounts[from] -= amount; accounts[to] += amount; ntransacts++; if (ntransacts % NTEST == 0) test(); }

public class UnsynchBankTest { public static void main(string[] args) { Bank b = new Bank(NACCOUNTS, INITIAL_BALANCE); int i; for (i = 0; i < NACCOUNTS; i++) { TransferThread t = new TransferThread(b, i, INITIAL_BALANCE); t.setpriority(thread.norm_priority + i % 2); t.start(); } }

public class Bank { public Bank(int n, int initialbalance) { accounts = new int[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialbalance; ntransacts = 0; } public void transfer(int from, int to, int amount) { if (accounts[from] < amount) return; accounts[from] -= amount; accounts[to] += amount; ntransacts++; if (ntransacts % NTEST == 0) test(); }

accounts[to] += amount; // is not an atomic operation load accounts[to] in some register add amount to that register save the register in accounts[to]

thread t1, amount = 500 thread t2, amount = 1000 both attempting to add their amount to accounts[7] trace done in class many scenarios, and several may be OK but many will not be OK solution: synchronized

All objects in Java have a lock associated with it Bank boa = new Bank(10, 10000); The object boa refers to a bank with 10 accounts each initially containing $10,000 There is a lock associated with that object NOTE: the lock is associated with the object, not with code

when a thread enters a synchronized method (or block of code), the object becomes locked if another thread attempts to enter any synchronized method for the same object, it becomes blocked when the thread who holds the lock exits the synchronized method, it unlocks the object periodically, the thread scheduler activates the threads that are waiting for the lock; the 1 st one to run will check for the lock; if it is unlocked, that thread enters; otherwise it blocks itself again

interrupt(), isinterrupted(), interrupted() avoid the deprecated methods stop(), resume() Methods that are inherited from Object: wait() the running thread must own this object s monitor (key); it causes the running thread to block and give up the key until another thread calls notify() or notifyall() notify() the running thread must own this object s monitor (key); it wakes up exactly one of the threads that are waiting on the object notifyall() similar to the above, but wakes up all waiting thread on that object

public synchronized void transfer(int from, int to, int amount) { try { while (accounts[from] < amount) wait(); accounts[from] -= amount; accounts[to] += amount; ntransacts++; notifyall(); if (ntransacts % NTEST == 0) test(); } catch(interruptedexception e) { // handle the exception } }