简体   繁体   中英

Access flags in synchronized methods?

I was looking around some pdf's from a university class and I noticed this code part:

public class MyMemoryElements {
    private String x = "";

    public MyMemoryElements(String message){
        this.x = message;
    }

    @Override
    public boolean equals(Object o){
        if(o instanceof MyMemoryElements ){
            MyMemoryElements tmp = (MyMemoryElements)o;
            if(tmp.toString().equalsIgnoreCase(this.x))
               return true;
            return false;
        }
        return false;

    }

    @Override
    public String toString(){
        return this.x;
   }
}

and the main code:

public class MainMemory {
   private Vector<MyMemoryElements> storage;
   private boolean canAccess = true;
   private int counter = -1;

   public MainMemory(){
       storage = new Vector<MyMemoryElements>();
   }

   public synchronized MyMemoryElements take(String s) {
       System.out.print("Method take has been invoked by "+s+". Element is:");
       while (!canAccess || storage.size()==counter+1) {
           try {
               wait();
           } catch (InterruptedException e) {}
       }
       canAccess = false;
       counter++;
       MyMemoryElements x = storage.elementAt(counter);
       try {
           Thread.sleep(10000);
       } catch (InterruptedException ex) {}
       notifyAll();
       System.out.println(x.toString());
       canAccess = true;
       return x;
   }

   public synchronized void update(MyMemoryElements element) {
       System.out.println("Producer is inserting element "+ element.toString());
       while (!canAccess) {
           try { 
               wait();
           } catch (InterruptedException e) {}
       }
       canAccess = false; 
       this.storage.add(element);
       notifyAll();
       canAccess = true;
   }
}

I cannot seem to understand the need for the canAccess variable considering the methods are synchronized (nor the reason the flag changes after notifyAll and not before)

EDIT : An additional question: Is there any point in all of this code? I mean all it does is get and add something to the vector. Aren't those actions synchronized already on vectors? All this code just so we can get a few prints in?

I agree - there is no need for these extra checks, given that the methods are marked synchronized .

(Looks like someone wanted to be really, really sure that there were no synchronization issues. :-)

Ironically, it could be argued that canAccess is not thread-safe. So even without the methods being synchronized, this would not necessarily be a suitable alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM