Lab 6 - Synchronization Problems

Q1. Consider the following code for an unbounded buffer.

import java.util.*;
 
public class UnBoundedBuffer {
 
  private ArrayList buffer = new ArrayList();//to buffer items
 
  /**
   * put() is called by Producer thread
   */
  public synchronized void put(Object o) {
    buffer.add(o);
  }
 
  /**
   * take() is called by Consumer thread
   */
  public synchronized Object take() throws InterruptedException {
    while(buffer.size() == 0) wait;
    return buffer.remove(0); //remove first item
  } 
}

Assume that there are many Producer threads and many consumer threads which are running concurrently
in an infinite loop. Producers are calling put() and Consumers are calling take().
(i) What are synchronization problems that can happen?
(ii) How would you change the above unbounded buffer code to solve the problems? Your solution should be fair to both the Producers and Consumers - none of Producers or Consumers should starvation

2. Consider three threads t1, t2 and t3 which use three semaphores s1,s2 and s3 as shown below


i) Will t1, t2 and t3 go into a deadlock? Why or why not? Explain your answer.

MCQs

1) What is the minimum numbers of threads and resources that can lead to a deadlock?
a) 1 thread and 2 resources
b) 2 threads and 1 resource
c) 1 thread and 1 resource
d) 2 threads and 2 resources

2) Which of the following is true about starvation?
a) all the threads/processes are blocked
b) some of threads processes are blocked
c) starvation may automatically go away after some time
d) none of the above

3) Which of the following is true about livelock?
a) Livelock is same as deadlock
b) In livelock some threads are running and some are bocked
c) In livelock all threads are blocked
d) In livelock all threads are running but not making any progress

4. Which one of the following conditions should be prevented from happening to avoid a deadlock?
a) Resource preemption
b) Mutual exclusion
c) Wait for cycle
d) Hold and wait

5. Deadlocks can be prevented by using
a) synchronized
b) semaphores
c) locks
d) none of the above

6. Starvation can be prevented by using
a) synchronized
b) semaphores
c) locks
d) none of the above

7. Livelocks can be prevented by using
a) synchronized
b) semaphores
c) locks
d) none of the above

Short Answer Questions

Please write answers to these questions in your notebooks because that is what you will need to do for the exam!


1. What are differences between deadlock and livelock?
2. What are the differences between deadlock and starvation?
3. Give an example of a situation where the dining philisophers go into a livelock.