Multi-Threading Dr. M. Khamis. Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g.

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)
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Mutual Exclusion.
1 Java threads: synchronization. 2 Thread states 1.New: created with the new operator (not yet started) 2.Runnable: either running or ready to run 3.Blocked:
Chapter 9 (Horstmann’s Book) Multithreading Hwajung Lee.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 5 Multithreading and.
Java How to Program, 9/e CET 3640 Professor: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Multithreading The objectives of this chapter are:
1 L49 Multithreading (1). 2 OBJECTIVES  What threads are and why they are useful.  How threads enable you to manage concurrent activities.  The life.
Monitors and Blocking Synchronization By Tal Walter.
ThreadThread Thread Basics Thread Synchronization Animations.
Java How to Program, 9/e CET 3640 Professor: Dr. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
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.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
CSE 219 Computer Science III Multithreaded Issues.
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
1 CMSC 341: Data Structures Nilanjan Banerjee Data Structures University of Maryland Baltimore County
Multithreading : synchronization. Avanced Programming 2004, Based on LYS Stefanus’s slides slide 4.2 Solving the Race Condition Problem A thread must.
Semaphores, Locks and Monitors By Samah Ibrahim And Dena Missak.
CSE 501N Fall ‘09 23: Advanced Multithreading: Synchronization and Thread-Safety December 1, 2009 Nick Leidenfrost.
Internet Software Development Controlling Threads Paul J Krause.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
CSC321 Concurrent Programming: §5 Monitors 1 Section 5 Monitors.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Multithreading Chapter Introduction Consider ability of human body to ___________ –Breathing, heartbeat, chew gum, walk … In many situations we.
Java Thread and Memory Model
Dr. R R DOCSIT, Dr BAMU. Basic Java :Multi Threading Cont. 2 Objectives of This Session Explain Synchronization in threads Demonstrate use of.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
SPL/2010 Guarded Methods and Waiting 1. SPL/2010 Reminder! ● Concurrency problem: asynchronous modifications to object states lead to failure of thread.
Threads in Java1 Concurrency Synchronizing threads, thread pools, etc.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Java Threads 11 Threading and Concurrent Programming in Java Synchronization D.W. Denbo Synchronization D.W. Denbo.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Internet Computing Module II. Threads – Multithreaded programs, thread Priorities and Thread Synchronization.
Semaphores Chapter 6. Semaphores are a simple, but successful and widely used, construct.
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.
1 Threads in Java Jingdi Wang. 2 Introduction A thread is a single sequence of execution within a program Multithreading involves multiple threads of.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Synchronization (Threads Accessing Shared Data). Contents I.The Bank Transfer Problem II.Doing a Simulation on the Bank Transfer Problem III.New Requirement:
Threads in Java Jaanus Pöial, PhD Tallinn, Estonia.
Multithreading / Concurrency
Multithreading.
Multithreaded Programming in Java
Multithreading Chapter 9.
23 Multithreading.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Multithreading Chapter 23.
Multithreading.
Multithreading.
Multithreaded Programming
Dr. Mustafa Cem Kasapbaşı
Semaphores Chapter 6.
Computer Science 2 06A-Java Multithreading
CSE 153 Design of Operating Systems Winter 19
Threads and Multithreading
Software Engineering and Architecture
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Multi-Threading Dr. M. Khamis

Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g. a text editor printing and spell-checking text. Threads are lightweight tasks: 1) they share the same address space 2) they cooperatively share the same process 3) inter-thread communication is inexpensive 4) context-switching from one thread to another is low-cost Java multi-tasking is thread-based.

Reasons for Multi-Threading Multi-threading enables to write efficient programs that make the maximum use of the CPU, keeping the idle time to a minimum. There is plenty of idle time for interactive, networked applications: 1) the transmission rate of data over a network is much slower than the rate at which the computer can process it

Reasons for Multi-Threading 2) local file system resources can be read and written at a much slower rate than can be processed by the CPU 3) of course, user input is much slower than the computer

Threads: Model Thread exist in several states: 1) ready to run 2) running 3) a running thread can be suspended 4) a suspended thread can be resumed 5) a thread can be blocked when waiting for a resource 6) a thread can be terminated Once terminated, a thread cannot be resumed.

Threads: Priorities Every thread is assigned priority – an integer number to decide when to switch from one running thread to the next (context-switching). Rules for context switching: 1) a thread can voluntarily relinquish control (sleeping, blocking on I/O, etc.),

Threads: Priorities then the highest-priority ready to run thread is given the CPU. 2) a thread can be preempted by a higher- priority thread – a lower-priority thread is suspended When two equal-priority threads are competing for CPU time, which one is chosen depends on the operating system

Synchronization In multithreading application more than one thread access data concurrently. Ex. Assume 2-threads the first adds 500 to specific account and the other adds 900.

Race Condition Thread 1, – Read the account balance to CPU register. – Add 500 to the content of the register. Then interrupted before register content is stored back into account Thread 2 repeat what thread 1 done to add 900, then. Thread 1 resume work to find the final account value is 5500 instead of 6400.

Threads: Synchronization Multi-threading introduces asynchronous behaviour to a program. Multi-threading introduces asynchronous behaviour to a program How to ensure synchronous behaviour when we need it? For instance, how to prevent two threads from simultaneously writing and reading the same object? Java implementation of monitors:

Threads: Synchronization 1) classes can define so-called synchronized methods 2) each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called 3) once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object

Synchronization :using Lock object (called ReentrantLock) Steps: 1. Defined Lock object (Lockob) as: – Lock lockob= new ReentrantLock(); 2. Use lockob with the Critical section as follow: Lockob.block() ; Try{ Critical section } Finally{ Lockob.unblock() ; }

Comparison of unsynchronized and synchronized threads

The Methods of Lock class The Lock class exists in package called Java.util.concurrent.locks, has following methods: void lock() Acquires this lock; blocks if the lock is currently owned by another thread void unlock() Release this lock.

Constructors of ReentrantLock class The ReentrantLock class exists in Java.util.concurrent.ReentrantLock has the following constructors ReentrantLock() – used to construct a reentrant lock to protect the critical section (default). ReentrantLock(boolean fair) – As above constructor, but with fairness guarantee (has significant drag on performance).

Conditional Objects (Construction) If thread, to enter section, needs condition to fulfilled in this case we use the conditional lock object (conditional variable). Class bank Constructs array of double to keep account of the bank customers and to transfer amount of any account, it should check the corresponding account as follow: While (!(bank.getbalance(from)) >= amount) ; bank.transfer(from, to, amount) ;

Conditional Objects (Continued) While (!(bank.getbalance(from)) >= amount) ; // the thread should deactivated until account balance changes bank.transfer(from, to, amount) ; Unless the thread blocks, it will wastes the CPU time and consumes quantum in busy waiting. Defined Conditional Lock object (sufficientFunds) as follow: Lock lockob= new ReentrantLock(); Condition sufficientFunds= lockob.newCondition()

lockob.lock() ; Try{ While (!(bank.getbalance(from)) >= amount) sufficientFunds.await() ; // deactivate the thread (waiting.. Not Runnable) bank.transfer(from, to, amount) ; sufficientFunds.signallAll() ; //reactivate waiting threads (runnable again) } finally { lockob.unlock() ; } – Lock object can have one or more conditional objects. The new condition on lock object is obtained by calling new lockob.newCondition() ; Conditional Objects (how to use?)

Conditional Lock and Deadlock Waiting thread waits until another thread executing signallAll(), if no such thread then the thread will wait indefinitely (program hangs). In the above example the waiting threads take another chance to inspect the condition when the accounts change.

Conditional Lock and Deadlock Signal(): Activating only one thread which is chosen randomly (more efficient) and the plenty is the danger of finding the selected thread itself blocked as the condition to continue is not satisfied yet (leads to deadlock). N.B. The Thread Can Only call await(), signallAll, or signal() when it owns the lock of the condition.

Conditional Lock Let every thing goes right but the price is the program will run more slower than before using the lock. Using the Lock object in precise manner is challenging since it can lead to deadlock. API of java.util.concurrent.locks.lock – Condition newCondition() Return a condition object that is associated with lock

API java.util.concurrent.locks.Condition void await() Put the thread on wail set for this condition. void signalAll() Unblock all threads in the wait set for this condition. void signal() Unblock one random thread from the wait set for this condition.

Summary of Lock Protects section of code, allowing only one thread to execute code at time. Lock can have one or more conditional lock. Each conditional object manages threads that have entered a protected code section but they cannot proceed.

Synchronized Keyword and its Equivalent Each object in java has intrinsic lock object. If a method is declared with keyword “synchronized”, then the object lock protect the whole method, as follow: public synchronized void method(){ method body… } public synchronized void method(){ Try{ this.intinisic.lock(); mehod body….. }finally{ this.intrinsic.unblock() ;}

Synchronized Keyword It is legal to declare static method with “synchronized” The transfer method declaration with “synchronized” public synchronized void transfer(int from, int to,doublr amount){ while (account[from] < amount) wait() ; account[from] -= amount ; account[to]+= amount; notifyAll() ; }

Limitations of Intrinsic Lock You cannot interrupt thread that is trying to acquire a lock. You cannot specify a timeout when trying to acquire a lock. Having a single condition per lock can be inefficient

What you should use in your code? If synchronized keyword works with you use it as you will write less code and less room for error Use lock/condition if you need additional power that this constructs give you.

API java.lang.object void notifyAll(); Unblocks all threads that called wait on this object. This is called only from within synchronized method. void wait() Wait thread until it is notified. Called only from within synchronized method. void wait(long msec) void wait(long msec, int nsec)

API java.lang.object void notify() Unblocks one thread selected randomly from the threads wait on this object. This is called only from within synchronized method. All the above methods throws IllegalMonitorStateException if the current thread is not the owner of the object’s lock.

Read-Write Lock Class ReentrantReadWriteLock is used to allow threads sharing data for read and write. Some thread that read has to continue while those threads to write have to implement mutual exclusion.

Steps of read write lock 1. Construct ReentrantReadWriteLock object. ReentrantReadWriteLock rwl= new ReentrantReadWriteLock() ; 2. Extract read and write locks as follow: private lock readlock= rwl.readLock(); Private lock writelock= rwl.writeLock();

Example Use read lock in all accessors : public double gettotalbalance(){ readlock.lock() Try{ ……. }finally{ readlock.unlock() ; }

Example Use write lock in mutators public double transfer(){ rwritelock.lock() Try{ ……. }finally{ writelock.unlock() ; }

Synchronized block Every java object has a lock, a thread can acquire a lock by calling synchronized method. There is second mechanism for acquiring the lock, by entering a synchronized block. This is done as: synchronized(obj){ critical section }

Example public class Bank{ object obj= new object(); double [] accounts; public void transfer(){ synchronized(obj) { account[from]-= account[from] ; account[to]+= account[to] ; }

Lock testing and time out A thread wait indefinitely when it calls the lock() method to acquire lock which is acquired by another thread. tryLock() method :tries to acquire a lock and return true if it was successful. Otherwise, it immediately returns false and the thread go off and do something else.

Example If (mylock.tryLock()){ //now thread owns the lock… Try {….} Finally{ mylock.unlock(); } }else { //do something else }

Lock testing and time out mylock.trylock(100,TimeUnit.MILLISECOND S) Time unit is enumeration SECONDS,MILLISECONDS, MICOSECONDS, NANOSECONDS If thread is interrupted while it waiting to acquire lock, the interrupted thread continues to be blocked until the lock is avialable.

Lock testing and time out If trylock() is interrupted with timeout, then InterruptedException is thrown. This is useful because it causes the program to break the deadlock. lockInterruptibly() method is used as trylock() method with infinite timeout. When you wait on condition, also time out can be used mycondition.await(100, TimeUnit.MILLISECONDS)

Lock testing and time out This await method returns, if another thread has activated this thread by call signal() or signallAll(), or the time out is elapsed.

API boolean trylock() Tries to acquire lock without blocking; if lock is available even if fair locking and other threads have been waiting.

API boolean trylock(long time, TimeUnit time) Tries to acquire lock blocking not more than the given time, return true if it successful void lockInterruptibly() Tries to acquire lock blocking indefinitely, throws exception if the thread is interrupted.

API boolean await(long time, TimeUnit time) Enter wait set for this condition and removed when time is elapsed or signalled by another thread.return false in case of time out and false otherwise void awaitUnInterruptibly() Enter wait set for a condition until thread is removed from the wait set if thread is interrupted this method doesn,t throws exception.

Blocking Queue If you want to stay away from low level implementation of implementing mutual execution for the critical section, you have to use higher level implementation such as blocking queue. – Useful in case of producer consumer. – Instead of performing the transfer directly; the transfer thread put the transfer object on a queue and another thread remove objects from the queue and carries out the transfers.

Blocking Queue No synchronization is necessary, the implementation of threadsafe queue classes had to worry about the lock, not you. Useful for coordination between multiple threads. Blocking queue cause the thread to wait when it tries to add element in case of fullness of the queue. Also when thread need to remove object of the empty queue.

Blocking Queue It balance load by this way between producers and consumers. Add(), element(), offer(), peek(), poll(), put(), remove() and take(). All are defined methods for the blocking queue.

addAdds an elementThrows IllegalStateException when Q is full element Returns the head element Throws a NoSuchElementException if Q is empty offerAdds element and return true Returns false if the Q is full peekReturns the head element Returns null if Q is empty pollRemoves and return the head element Returns null if Q is empty putAdds an elementBlocks if the Q is full removeRemoves and return the head element Throws a NoSuchElementException if Q is empty takeRemoves and return the head element Blocks if the Q is empty

Blocking Queues There is variations of offer and poll methods with timeout: Object head = q.poll() ;

Monitor Concept Locks and Conditions are very powerful for thread synchronization, but they are not object oriented. On the contrary Monitor has the following characteristics: – Class with only private fields. – Each object of this class has associated lock. – All methods are synchronized by that lock. – Lock can have any number of conditions.