java - How do you insure mutual exclusion for data structures? -


i heard same rule applies variables doesn't apply when we're talking data structures. true?

for instance, this, fine

public class synchronizedcounter {     private int c = 0;      public synchronized void increment() {         c++;     }      public synchronized void decrement() {         c--;     }      public synchronized int value() {         return c;     } } 

does not mean following work flawlessly.

public class synchronizeddatastructures {     private arraylist<string> c = new arraylist<string>();      public synchronized void add1(element) {         c.add(element);     }      public synchronized void clear1() {         c.clear();     }      public synchronized int value() {         return c;     } } 

is true , can make work data structures?

if change add1(element) add1(string element), , remove value() method, compile, , thread safe.

you need method correctly accessing contents of list. e.g.

public synchronized int value(int index) {     return c.get(index); } 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -