Mutual Exclusion - PowerPoint PPT Presentation

About This Presentation
Title:

Mutual Exclusion

Description:

Imagine what might happen if two or more threads are accessing the same object at the same time. ... Depending on the order in which the object is accessed, the ... – PowerPoint PPT presentation

Number of Views:16
Avg rating:3.0/5.0
Slides: 6
Provided by: Jasm154
Category:

less

Transcript and Presenter's Notes

Title: Mutual Exclusion


1
Mutual Exclusion
2
Race Condition
  • In many practical multithreaded application, two
    or more threads need to share the same object.
  • Imagine what might happen if two or more threads
    are accessing the same object at the same time.
  • Depending on the order in which the object is
    accessed, the corrupted objects may result.
  • Race condition refers to such situation.

3
Setting Mutual Exclusion Zone
  • You can set a method as a restricted region by
    defining it as synchronized.
  • public synchronized void access()
  • You can also set a block of code as a restricted
    region by enclosing it with
  • synchronized
  • // you code here
  • Every Java object has the key(called monitor) to
    these synchronized region. (Only one key per an
    object)
  • For a thread to enter these synchronized region
    should get the key(of the object).
  • Since the key can be assigned to only one thread
    at a time, we can avoid race condition.

4
How To Get a Key?
  • A thread is assigned the key when it enters a
    synchronized region if the key is not owned by
    any other thread.
  • In other words, no thread is inside any of the
    synchronized regions.
  • When multiple threads try to enter the region at
    the same time, only one thread is picked up and
    given the key.
  • When a thread is inside a synchronized region,
    any other threads which access the region are put
    into waiting queue.
  • We refer this situation as waiting for the key.
  • When a thread returns the key(or finished with
    the region), the first thread in the waiting
    queue is picked up and given the key.

5
Giving Up the Key
  • Quite often, a thread may need to suspend itself
    inside a synchronized region. (See the handout)
  • wait() method is used in such situation.
  • When a thread calls wait(), it puts itself into
    another waiting queue.
  • A thread in this queue can return to synchronized
    region only when other thread calls
    notify()/notifyAll() method.
  • In other words, it is another thread that can
    wake up suspended threads.
  • Note that a suspended thread can never be
    rescheduled until it is notified.
Write a Comment
User Comments (0)
About PowerShow.com