Question:
Since vector is synchronized, is below code thread safe? If 2 threads are running below code, what will happen?
if(!vector.contains(element)) {
vector.add(element);
}
Rong answer: not thread safe, because another thread could add element in between vector.contains(element) and vector.add(element);
(my own question, not from interview, but just my own thought: What does "Vector is synchronized" mean?
my own answer: It means all methods that can update data are synchronized. So calling each single method is thread safe,
but a transaction involving 2 synchronized methods is not thread safe. Only if a transaction is atomic, we can say it's thread safe.
Question:
synchronize(obj) {
obj.wait();
}
if 2 threads are running above code the same time, what will happen?
Rong answer: one thread acquire lock, then release lock, another thread acquire lock and then release lock, both wait forever.
follow up question: if a third thread call obj.notifyAll(), what will happen?
Rong answer: both waiting threads will be woken up, then one thread acquire lock and finish, then another thread acquire lock and finish.
Question:
synchronize(obj) {
print("A");
obj.wait();
Thread.sleep(100000000);
}
what will happen if 2 threads are running above code?
Rong answer: both print "A" then wait; if notified by a third thread, then will sleep for a long time.