5

Is there any danger, if im using one Vector(java.util.Vector) on my server program when im accessing it from multiple threads only for reading? (myvector .size() .get() ...) For writing im using synchronized methods. Thank you.

4 Answers 4

22

As stated above, every single method of Vector is thread-safe by its own because of synchronized modifiers. But, if you need some complex operations, such as get() or add() based on condition which is related to the same vector, this is not thread-safe. See example below:

if (vector.size() > 0) {
    System.out.println(vector.get(0));
}

This code has a race condition between size() and get() - the size of vector might be changed by other thread after our thread verified the vector is not empty, and thus get() call may return unexpected results. To avoid this, the sample above should be changed like this:

synchronized (vector) {
    if (vector.size() > 0) {
        System.out.println(vector.get(0));
    }
}

Now this "get-if-not-empty" operation is atomic and race condition-free.

11

Vector is a thread-safe collection - all its methods are synchronized by default. This is why it's recommended to use ArrayList instead - it's not thread-safe which results in a better performance for single-thread applications.

2
  • Of course, ArrayList is thread-safe if no thread ever writes the array after it has been safely published. (But don't forget, "no thread" means, not even the main thread.) Commented Apr 23, 2014 at 14:23
  • 1
    Why is there a difference for single thread applications? If there is never any other thread locking the synchronized methods, wouldn't it be virtually the same? Is there such an overhead for the synchronized mechanism added even without locking/blocking?
    – Nom1fan
    Commented Jan 22, 2020 at 16:48
3

The java.util.Vector methods are all synchronized. So using it from multiple threads is "safe". You only need to synchronize if you need a read-evaluate-write process to be atomic. Synchronizing your own methods does not necessarily make your code thread-safe for those scenarios. If the shared state is the Vector object, then you need to synchronize on the instance of your Vector, not on an instance of your own classes.

1
  • 'If the shared state is the Vector object, then you need to synchronize on the instance of your Vector', thanks that also helped me :)
    – Smarty77
    Commented Apr 23, 2014 at 13:59
1

Vector class is thread safe (size, get, set methods are synchronized), but if you want to achieve better performance you should try to use CopyOnWriteArrayList or Collections.synchronizedList instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.