class server {
private Vector<Msg> v = new ...
...
public void deliver(Msg msg) {
...
v.add(msg);
}
}
class client {
private server s = server.getInstance(); // singleton
...
public void propose() {
s.deliver(new Msg( ... ));
}
}
If multiple concurrent clients pass a value (Msg object) to a server by means of a [non-synchronized!] deliver method, is it feasible to assume that whatever client calls [or, more precisely, enters] deliver first will store its value first in v – or is making deliver synchronized mandatory to make this assumption hold?
No, you cannot make such assumption because the scheduler can interrupt current thread that is inside
deliver()but haven’t yet made it tov.add(msg). Scheduler switches to another thread that callsdeliver()(afterwards) but manages to finish the wholedeliver()invocation.If you synchronize
deliver()method, it won’t prevent the scheduler from interrupting the execution in the meantime. But no other thread will be capable of entering that method while the first thread holds the lock si eventually the scheduler will wake up the original thread and let him finish.BTW
Vectoris quite ancient, there are better alternatives.