Java – Vector Synchronization

ArrayList is not Synchronized: We get odd results when we try to add elements into ArrayList from multiple threads.

import java.util.*;
class Test
{
            static ArrayList<Integer> list = new ArrayList<Integer>();
}
class First extends Thread
{
            public void run(){
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Test.list.add(i);
                        }
            }
}
class Second extends Thread
{
            public void run(){
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Test.list.add(i);
                        }
            }
}
class Code
{
            public static void main(String[] args) throws Exception {
                        First f = new First();
                        Second s = new Second();
                        f.start();
                        s.start();
                        f.join();
                        s.join();
                        System.out.println(“List size is : ” + Test.list.size());
            }
}

Output:           List size is : 166987

Vector is synchronized by default: Vector is thread safe, hence we get perfect results when we try to add elements from multiple threads

import java.util.*;
class Test
{
            static Vector<Integer> list = new Vector<Integer>();
}
class First extends Thread
{
            public void run(){
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Test.list.add(i);
                        }
            }
}
class Second extends Thread
{
            public void run(){
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Test.list.add(i);
                        }
            }
}
class Code
{
            public static void main(String[] args) throws Exception
            {
                        First f = new First();
                        Second s = new Second();
                        f.start();
                        s.start();
                        f.join();
                        s.join();
                        System.out.println(“Vector size is : ” + Test.list.size());
            }
}

Output:           Vector size is : 200000

Scroll to Top