Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unsynchronization make ArrayList faster and less secure?

I read the following statement:

ArrayLists are unsynchronized and therefore faster than Vector, but less secure in a multithreaded environment.

I would like to know why unsynchronization can improve the speed, and why it will be less secure?

like image 987
user288609 Avatar asked Dec 10 '22 08:12

user288609


2 Answers

I will try to address both of your questions:

Improve speed

If the ArrayList were synchronized and multiple threads were trying to read data out of the list at the same time, the threads would have to wait to get an exclusive lock on the list. By leaving the list unsynchronized, the threads don't have to wait and the program will run faster.

Unsafe

If multiple threads are reading and writing to a list at the same time, the threads can have unstable view of the list, and this can cause instability in multi-threaded programs.

like image 154
jjnguy Avatar answered Dec 11 '22 21:12

jjnguy


The whole point of synchronization is that it means only one thread has access to an object at any given time. Take a box of chocolates as an example. If the box is synchronized (Vector), and you get there first, no one else can take any and you get your pick. If the box is NOT synchronized (ArrayList), anyone walking by can snag a chocolate - It will disappear faster, but you may not get the ones you want.

like image 31
josh.trow Avatar answered Dec 11 '22 22:12

josh.trow