Why is the following Vector code broken exactly?

follows from : Synchronization in Vectors in Java

Why is the below code broken as far as synchronization is considered? Is the vector class not synchronized on its own object (this)?

  // BROKEN CODE, needs external synchronization
 // only add an element if the vector is empty
     if(vector.isEmpty())
         vector.add(anElement);

UPDATE:

Going by the answers(from jon Skeet and Pshemo) below, doesn't it render vectors practically useless(that we have arraylist)?

Because we need to synchronise manually anyway for any practical use. If yes, what is stopping Java from marking vector deprecated atleast?

Jon Skeet
people
quotationmark

Is the vector class not synchronized on its own object (this)?

Yes, but only for each individual operation.

Here we have two operations:

if (vector.isEmpty())
    vector.add(anElement);

It's possible that between the check of isempty and the add call, a different thread could add an item. The fix is to add synchronization over the combined operation:

synchronized (vector) {
    if (vector.isEmpty()) {
        vector.add(anElement);
    }
}

people

See more on this question at Stackoverflow