1

When do we use synchronized ArrayList? We already have Vector which is synchronized.

Dheeraj Bhaskar
  • 18,633
  • 9
  • 63
  • 66
giri
  • 26,773
  • 63
  • 143
  • 176
  • 1
    I nominate this question for further editing: there's useful content there. Example title: "Why do we need synchronized ArrayLists when we already have Vectors?" – Bob Cross Jan 20 '10 at 20:50
  • You can 'synchronize' an ArrayList by using java.util.Collections - is that what you meant in your question? This may be preferable to Vector becuause it implements the Collection and List interfaces – Dan Jan 20 '10 at 21:26

5 Answers5

16

I think that you've got this wrong. ArrayList is unsynchronized, Vector is.

Being synchronized means that every operation is thread safe - if you use the same vector from two threads at the same time, they can't corrupt the state. However, this makes it slower.

If you are working in a single threaded environment (or the list is limited to a thread and never shared), use ArrayList. If you are working with multiple threads that share the same collection, either use Vector, or use ArrayList but synchronize in some other way (e.g., manually or via a wrapper).

Uri
  • 88,451
  • 51
  • 221
  • 321
  • 2
    Vector is pretty much obsolete, see http://stackoverflow.com/questions/1386275/why-java-vector-class-is-considered-obsolete-or-deprecated - "Vector synchronizes on each individual operation. That's almost never what you want to do." – Pool Jan 20 '10 at 20:46
  • I agree. I haven't used Vectors in a long long time. But I still see them a lot in code. ArrayLists bother me because of the naming. It's like a mix of two things that should not be part of the same word. – Uri Jan 20 '10 at 20:57
4

ArrayList is not synchronized via http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html

Rob Spieldenner
  • 1,697
  • 1
  • 16
  • 26
3

ArrayList is not synchronized out of the box.

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

This avoids some performance issues in situations where you know that you won't need thread safety (e.g., entirely encapsulated private data). However both ArrayList and Vector have issues when using iterators over them: when iterating through either type of collection, if data is added or removed, you will throw a ConcurrentModificationException:

Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(...));

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

ArrayList comes in a variety of useful flavors, however, while Vector does not. My personal favorite is the CopyOnWriteArrayList:

A thread-safe variant of ArrayList in which all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

This is ordinarily too costly, but may be more efficient than alternatives when traversal operations vastly outnumber mutations, and is useful when you cannot or don't want to synchronize traversals, yet need to preclude interference among concurrent threads. The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.

CopyOnWriteArrayLists are tremendously useful in GUI work, especially in situations where you are displaying an updating set of data (e.g., moving icons on a screen). If you can tolerate having your displayed list of data be one frame out of date (because your producer thread is slightly behind your graphical update thread), CopyOnWriteArrayLists are the perfect data structure.

Community
  • 1
  • 1
Bob Cross
  • 22,116
  • 12
  • 58
  • 95
  • 1
    +1 for beating me to recommending COWAL. Vector is so unloved these days I'm surprised the entire class hasn't been deprecated; CopyOnWriteArrayList is a lovely little critter that lets you avoid all manner of problems. – BlairHippo Jan 20 '10 at 20:41
  • @BlairHippo, I agree. The fact that you can ignore the possibility of someone writing over your data while you're reading it make the world a sunnier place. – Bob Cross Jan 20 '10 at 20:48
  • Note that COWAL has one very minor issue; library methods designed to work on Collections aren't always anticipating the possibility that a COWAL might be supplied; for example, a `static getLastElement(List list)` method would typically be implemented `synchronized (list) { return list.get(list.size() - 1); }`, which would be completely broken for a COWAL. Just a minor caveat, that's all. – Kevin Bourrillion Jan 20 '10 at 22:22
  • As long as we're discussing sneaky gotchas: CopyOnWriteArrayList.subList() returns a List, not a COWAL, as one might expect. This can make for tear-out-your-hair frustrating bugs. (http://stackoverflow.com/questions/1527519/copyonwritearraylist-throwing-currentmodificationexception) :-) – BlairHippo Jan 20 '10 at 22:59
  • @BlairHippo: wow, I remember you asking that question and thinking "what? No.... Really? Ugh." Summary: everything about multithreading is hard. All the time. Up hill both ways. – Bob Cross Jan 21 '10 at 01:47
  • @Kevin, not only that, FindBugs has a detector for situations where util.concurrent data structures are used with synchronized. Very puzzling reports show up in your FindBugs reports when you synchronize(them). – Bob Cross Jan 21 '10 at 01:48
  • 1
    @Bob Cross: Don't forget the snow. Multithreading snows on you. And the snow is made of pain. Beautiful, crystallized pain. – BlairHippo Jan 21 '10 at 14:20
  • @BlairHippo, I yield the contest of poetic imagery to you, sir. Well played. Well played indeed. – Bob Cross Jan 21 '10 at 21:52
2

What does it mean array list is synchronized in java?

It means it is thread-safe.

  • Vectors are synchronized. Any method that touches the Vector's contents is thread safe.
  • ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe.
jldupont
  • 93,734
  • 56
  • 203
  • 318
0

I read ArrayList is synchronized in java..

But the array list api says that

Note that this implementation is not synchronized

So you use an ArrayList when you are sure that you wont be dealing with concurrency. Using Vector might be an overkill, and may result in performance issues.

Community
  • 1
  • 1
Tom
  • 43,810
  • 29
  • 138
  • 169