Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Vector Thread safety

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.

like image 278
Smarty77 Avatar asked Nov 27 '22 03:11

Smarty77


2 Answers

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.

like image 96
Alexey Malev Avatar answered Dec 05 '22 17:12

Alexey Malev


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.

like image 35
Denis Kulagin Avatar answered Dec 05 '22 18:12

Denis Kulagin