1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science.

Slides:



Advertisements
Similar presentations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Advertisements

Concurrency Important and difficult (Ada slides copied from Ed Schonberg)
Chapter 6: Process Synchronization
Concurrency 101 Shared state. Part 1: General Concepts 2.
1 Race Conditions When threads share access to a common object/data, they can conflict with each other and mess up the consistency of the object/data.
Locks (Java 1.5) Only one thread can hold a lock at once –Other threads that try to acquire it block (or become suspended) until lock becomes available.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
CS 11 java track: lecture 7 This week: Web tutorial:
Chapter 7 Threads  Threads & Processes  Multi Threading  Class Thread  Synchronized Methods  Wait & Notify.
CS444/CS544 Operating Systems Synchronization 2/16/2006 Prof. Searleman
Concurrency and Thread Yoshi. Two Ways to Create Thread Extending class Thread – Actually, we need to override the run method in class Thread Implementing.
Threads Load new page Page is loading Browser still responds to user (can read pages in other tabs)
1 L50 Multithreading (2). 2 OBJECTIVES  What producer/consumer relationships are and how they are implemented with multithreading.
Synchronization in Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads A thread is a program unit that is executed independently of other parts of the program A thread is a program unit that is executed independently.
ThreadThread Thread Basics Thread Synchronization Animations.
Definitions Process – An executing program
Process Synchronization Ch. 4.4 – Cooperating Processes Ch. 7 – Concurrency.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading.
Operating Systems CSE 411 CPU Management Oct Lecture 13 Instructor: Bhuvan Urgaonkar.
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
Concurrency Recitation – 2/24 Nisarg Raval Slides by Prof. Landon Cox.
A Bridge to Your First Computer Science Course Prof. H.E. Dunsmore Concurrent Programming Threads Synchronization.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Locks CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Threading and Concurrency Issues ● Creating Threads ● In Java ● Subclassing Thread ● Implementing Runnable ● Synchronization ● Immutable ● Synchronized.
1 Concurrent Languages – Part 1 COMP 640 Programming Languages.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Threads CS 3250 Some of these slides contain material by Professor Chuck Allison.
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
C# I 1 CSC 298 Threads. C# I 2 Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The execution.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
Internet Software Development Controlling Threads Paul J Krause.
Synchronizing threads, thread pools, etc.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Chapter 6 – Process Synchronisation (Pgs 225 – 267)
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
Multi-Threading in Java
Monitors CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
CS 151: Object-Oriented Design November 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 G53SRP: Java Concurrency Control (2) – wait/notify Chris Greenhalgh School of Computer Science.
CSC CSC 143 Threads. CSC Introducing Threads  A thread is a flow of control within a program  A piece of code that runs on its own. The.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Software Design 13.1 From controller to threads l Threads are lightweight processes (what’s a process?)  Threads are part of a single program, share state.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Multithreading / Concurrency
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
G53SRP: Resource Sharing Issues
Thread Synchronization
Threading And Parallel Programming Constructs
Multithreading.
Concurrency in Java Last Updated: Fall 2010 Paul Ammann SWE 619.
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Lecture 8 Thread Safety.
Presentation transcript:

1 G53SRP: Java Concurrency Control (1) - synchronisation Chris Greenhalgh School of Computer Science

2 Contents Overview of Java synchronisationOverview of Java synchronisation Instance methodsInstance methods Class methodsClass methods Synchronized blocksSynchronized blocks Additional NotesAdditional Notes DeadlockDeadlock SummarySummary Book: Wellings 3.1, 1.1 (deadlock)Book: Wellings 3.1, 1.1 (deadlock)

3 Synchronisation Overview Every Java object has an associated lockEvery Java object has an associated lock –Every class is also an object and has its own lock At most one thread can hold a lock at any timeAt most one thread can hold a lock at any time The lock is manipulated implicitly using the synchronized keyword…The lock is manipulated implicitly using the synchronized keyword… Object Lock Method

4 Synchronized methods If a method is declared synchronizedIf a method is declared synchronized –The calling thread obtains the lock on entry and releases the lock on exit (return or exception) –=> at most one thread can be active in a sync. method per object –= “monitor” Other methods are always openOther methods are always open Lock Sync. Method Sync. Method Unsync. Method Object

5 Example 1a: instance method public class MethodNoSyncTest { // account balance int balance; // method public void deposit() { balance = balance + 100; } // method public void withdraw() { balance = balance - 100; } … }public class MethodNoSyncTest { // account balance int balance; // method public void deposit() { balance = balance + 100; } // method public void withdraw() { balance = balance - 100; } … } Critical sections because: Modify shared state (shared memory)

6 Example 1a (cont.) class UpdateTask implements Runnable { public void run() { for (long i = 0; i < ; i++) { deposit(); withdraw(); } } } … balance = 100; Thread t1 = new Thread(new UpdateTask()); t1.start(); Thread t2 = new Thread(new UpdateTask()); t2.start(); t1.join(); t2.join();  final balance not 100: Interleaving of shared state reads/write  RW/WW conflicts  error  final balance not 100: Interleaving of shared state reads/write  RW/WW conflicts  error Watch for this

7 Example 1b public class MethodSyncTest { // account balance int balance; // method public synchronized void deposit() { balance = balance + 100; } // method public synchronized void withdraw() { balance = balance - 100; } … }public class MethodSyncTest { // account balance int balance; // method public synchronized void deposit() { balance = balance + 100; } // method public synchronized void withdraw() { balance = balance - 100; } … }  Final balance 100 – each method obtains instance lock and so runs to completion without interleaving  Final balance 100 – each method obtains instance lock and so runs to completion without interleaving

8 Example 1b Provided balance is only manipulated from synchronized methods all updates will be serialisedProvided balance is only manipulated from synchronized methods all updates will be serialised –i.e. “mutual exclusion”, “critical sections” N.B. each instance is independentN.B. each instance is independent –own balance, own lock What effect does locking have on speed of execution?What effect does locking have on speed of execution? –Considerably slower (time to acquire and release lock) Lock Unsync. Method Object - balance withdraw deposit

9 Example 2a: class method public class ClassMethodNoSyncTest { // account balance static int balance; // method public static void deposit() { balance = balance + 100; } // method public static void withdraw() { balance = balance - 100; } … }public class ClassMethodNoSyncTest { // account balance static int balance; // method public static void deposit() { balance = balance + 100; } // method public static void withdraw() { balance = balance - 100; } … }

10 Example 2a (cont.) static class UpdateTask implements Runnable { public void run() { for (long i = 0; i < ; i++) { deposit(); withdraw(); } } } … balance = 100; Thread t1 = new Thread(new UpdateTask()); t1.start(); Thread t2 = new Thread(new UpdateTask()); t2.start(); t1.join(); t2.join();  same as in case of shared instance variable (still shared state)  same as in case of shared instance variable (still shared state)

11 Example 2b public class ClassMethodSyncTest { // account balance static int balance; // method public static synchronized void deposit() { balance = balance + 100; } // method public static synchronized void withdraw() { balance = balance - 100; } … }public class ClassMethodSyncTest { // account balance static int balance; // method public static synchronized void deposit() { balance = balance + 100; } // method public static synchronized void withdraw() { balance = balance - 100; } … }  Correct execution – methods obtain class lock  Correct execution – methods obtain class lock

12 Example 2b Class has its own lockClass has its own lock –N.B. independent of all instance locks –=> class synchronized methods do NOT block instance synchronized methods or vice versa Class lock Unsync. Method Class object - balance (static) static withdraw deposit

13 Example 3a: synchronized block public class BlockSyncTest { // like NoSyncTest // account balance int balance; // method public void deposit() { balance = balance + 100; } // method public void withdraw() { balance = balance - 100; } … }public class BlockSyncTest { // like NoSyncTest // account balance int balance; // method public void deposit() { balance = balance + 100; } // method public void withdraw() { balance = balance - 100; } … }

14 Example 3a (cont.) class UpdateTask implements Runnable { UpdateTask(BlockSyncTest instance) { this.instance = instance; } BlockSyncTest instance;class UpdateTask implements Runnable { UpdateTask(BlockSyncTest instance) { this.instance = instance; } BlockSyncTest instance; public void run() { for (long i = 0; i < ; i++) { public void run() { for (long i = 0; i < ; i++) { synchronized(instance) { instance.deposit(); instance.withdraw(); } synchronized(instance) { instance.deposit(); instance.withdraw(); } } } }

15 Example 3a (cont.) BlockSyncTest instance = new BlockSyncTest(); instance.balance = 100 Thread t1 = new Thread (new UpdateTask(instance)); t1.start(); Thread t2 = new Thread (new UpdateTask(instance)); t2.start(); t1.join(); t2.join();BlockSyncTest instance = new BlockSyncTest(); instance.balance = 100 Thread t1 = new Thread (new UpdateTask(instance)); t1.start(); Thread t2 = new Thread (new UpdateTask(instance)); t2.start(); t1.join(); t2.join();  critical sections execute with lock on shared instance  critical sections execute with lock on shared instance Lock withdraw deposit instance - balance

16 Additional notes Object locks are re-entrantObject locks are re-entrant –i.e. a sychronized method or block can call other synchronized methods on the same object (lock) without blocking/deadlock Locks are implicitly released when block or method is leftLocks are implicitly released when block or method is left –Avoids problems with explicit lock/unlock of missing an unlock  deadlock

17 Additional notes: deadlock A synchronized method can call both synchronized and unsynchronized methods in other classesA synchronized method can call both synchronized and unsynchronized methods in other classes –The lock is still held This can result in deadlock…This can result in deadlock…

18 Example of deadlock thread A has lock on O1 and calls sync method on O2 while thread B has lock on O2 and calls sync method on O1thread A has lock on O1 and calls sync method on O2 while thread B has lock on O2 and calls sync method on O1 Lock m1 O1 Lock m2 O2 B A x

19 Requirements for deadlock Mutual exclusionMutual exclusion –Only one thread can use each resource (lock) Hold and waitHold and wait –Blocked threads hold onto locks No pre-emptionNo pre-emption –The system will not take away a lock from a blocked thread Circular waitCircular wait –A cycle of threads requiring resources held by the next

20 Summary Mutual exclusion is supported on Java by per- object locksMutual exclusion is supported on Java by per- object locks –A class is also an object ( MyClass.class ) Locks are re-entrantLocks are re-entrant Locks are implicitly manipulated by the JVMLocks are implicitly manipulated by the JVM Acquired by synchronized methodsAcquired by synchronized methods –Instance method  instance lock; class method  class lock Or synchronized(…) {…} blocksOr synchronized(…) {…} blocks Released automatically on leaving method/blockReleased automatically on leaving method/block