0

Hi all,
I know that Vector is synchronized,
when I run the following program

public class ClassA extends Thread{
static Vector<Integer > v=new Vector<Integer>();
public void run()
    {
        callMethod();

    }
    public   void callMethod() {
    System.out.println(v.size());
    v.add(0);
    System.out.println(v.size());
    v.remove(0);
    }
    public static void main(String[] args) {
         for(int i=0;i<1000;i++)
         {
            ClassA a=new ClassA();
             a.start();

         }
    }

When I run the above program i am expecting result as 0 1..0 1... 0 1.. because vector internally sychronized ,
but when i give sychronize in externally its working fine

i.e when i change method as public static synchronized void callMethod() { then its working fine

So vector sychnronization where it works
could any one help me
thanks in advance

2
Contributors
2
Replies
4
Views
4 Years
Discussion Span
Last Post by anand01
1

Vectors own methods are synchronised on the Vector instance, so if you call add on a Vector from one thread while another thread is executing a remove yhou should be OK.
Vetor knows nothing about your callMethod method, so it can do nothing about synchronising that. It does not / cannot know that you want the calls on lines 9 and 11 to be synchronised as one block.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.