How does Vector implement synchronization?

Answer Posted / azad bajaj

Almost all the methods in the Vector class are synchronized.
All the methods which either change (read or write) the
values, or change the size or the change the capacity of
the vector.
example method:

public synchronized void setElementAt(E obj, int index) {
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException
(index + " >= " + elementCount);
}
elementData[index] = obj;
}

or

public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException
(index + " >= " +

elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException
(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1,
elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc
do its work */
}

Is This Answer Correct ?    5 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is the output of the below java program?

821


Define iterator and methods in iterator?

748


How do you create immutable object in java?

791


Can we increase array size dynamically in java?

717


What is getkey () in java?

789


What is difference between static and final?

773


What are the methods used to implement for the key object in the hash map?

795


Explain the difference between abstraction and encapsulation.

742


What is the tradeoff between using an unordered array versus an ordered array?

925


How arrays are stored in memory in java?

717


What is a local, member and a class variable?

786


Difference between serialization and deserialization in java?

861


How do you include a string in java?

756


How to call one constructor from the other constructor ?

815


Can we assign null to double in java?

770