CSE 132 (Spring 2009)
Quiz 2

Name: _____________________________  Attend lab section: _________________________
  1. Recall that a Set's .iterator() has a boolean hasNext() and Object next() method.
    On the back, write code for a method public void lockSetAndRun(Set s, Runnable r) that obtains and holds a lock on every Object in Set s and then invokes the Runnable r while holding the locks. Use a helper method if necessary.
  2. Describe two different approaches to making the code below thread-safe. Show the changes that must be made to the code for each approach.
    public class Point {
       private double x, y;
       public Point(double x, double y) { 
          this.x = x; 
          this.y = y; 
       }
    
       public Point scale(double factor) {
          double oldX = x; 
          double oldY = y;
    
          x = factor * x;  
          y = factor * y;
    
          Point ans = new Point(x,y);
    
          x = oldX;
          y = oldY;
          return ans;
       }
       public double getX() { return x; }
       public double getY() { return y; }
    }
    
    
    
    
    
    
    
    
    
  3. Extra credit: What changes must be made in the class below to make it thread-safe?
    import java.util.Date;
    public class Foo {
       private static Date uniqueTimeStamp;
    
       public Foo() {  // constructors cannot be synchronized
          if (uniqueTimeStamp == null)
             uniqueTimeStamp = new Date();
       }
    
       // Should return same Date instance for all instances of Foo
       public Date getStartTime() { return uniqueTimeStamp; }
    }
    


Last modified 20:12:00 CST 11 January 2010 by Ron K. Cytron