what is meant by vector in Java is thread safe and synchronized, how is it made thread safe. I'm looking at internal details of implementation
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The methods are marked as
synchronized
. Check out the Synchronized Method tutorial.It is made "thread-safe" by merit of all its methods being synchronized (via the synchronized keyword), see the OpenJDK source code.
What the synchronized keyword does is that it prevents more than one thread from executing any of the synchronized methods at the same time. It is using a lock internally, that a thread has to obtain when entering of of those methods, and that the thread releases when it leaves the method.
Note that this does not really help much, because while it prevents inconsistent internal state of the vector, this does in no way guarantee a level of consistency on a higher level (a useful level for an application).
Consider this example that shows that you still need to use synchronization in your application code (so that you might just as well have used the unsynchronized ArrayList):
Please find the below excerpts from java api
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Vector
is considered 'thread-safe' because access the the internals of the Vector is synchronized. Methods such asadd()
,get()
,size()
, etc, are all synchronized such that modifications to the internal structure of theVector
and access to that internal structure cannot be processed simultaneously by separate threads.