ArrayList vs Vector - does this illustrate the difference in synchronization?

I am trying to understand the difference in the behavior of ArrayList and Vector. Is the following snippet in any way illustrating the difference in synchronization? The output for ArrayList (f1) is unpredictable, and the output for Vector (f2) is predictable. I think it might just be luck that f2 has a predictable conclusion, because changing f2 a bit to make the thread sleep even for ms (f3) causes an empty vector! What causes this?

public class D implements Runnable {
   ArrayList<Integer> al;
   Vector<Integer> vl;

   public D(ArrayList al_, Vector vl_) {
      al = al_;
      vl = vl_;
   }

   public void run() {
      if (al.size() < 20)
         f1();
      else
         f2();
   } // 1

   public void f1() {
      if (al.size() == 0)
         al.add(0);
      else
         al.add(al.get(al.size() - 1) + 1);
   }

   public void f2() {
      if (vl.size() == 0)
         vl.add(0);
      else
         vl.add(vl.get(vl.size() - 1) + 1);
   }

   public void f3() {
      if (vl.size() == 0) {
         try {
            Thread.sleep(1);
            vl.add(0);
         } catch (InterruptedException e) {
            System.out.println(e.getMessage());
         }
      } else {
         vl.add(vl.get(vl.size() - 1) + 1);
      }
   }

   public static void main(String... args) {
      Vector<Integer> vl = new Vector<Integer>(20);
      ArrayList<Integer> al = new ArrayList<Integer>(20);
      for (int i = 1; i < 40; i++) {
         new Thread(new D(al, vl), Integer.toString(i)).start();
      }
   }
}
+3
source share
4 answers

: vector, , (, NullPointerExceptions - ). , , size(), Vector , ArrayList ( , , ArrayLists , , , , /)

, , .

if (al.size() == 0)
   al.add(0);
else
   al.add(al.get(al.size() - 1) + 1);

(.. N , , [0..N)). , :

, 2 /. :

T1: size() # go to true branch of if
T2: size() # alas we again take the true branch.
T1: add(0)
T2: add(0) # ouch

size() 0. 0 . , .

, -, , size() add() . , ( JVM, , API , )

+4
0

Vectors are thread safe. ArrayLists no. This is why an ArrayList is faster than a vector. The link below has nice information about this.

http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-0622-vector.html

0
source

I am trying to understand the difference in the behavior of ArrayList and Vector

Vector synchronizedbut ArrayListnot. ArrayListnot thread safe.

Is the following snippet in any way illustrating the difference in synchronization?

It makes no difference, as Vectorthere is onlysunchronized

0
source

All Articles