Java consistent synchronization
Posted
by
ring0
on Stack Overflow
See other posts from Stack Overflow
or by ring0
Published on 2011-01-11T03:16:47Z
Indexed on
2011/01/11
3:55 UTC
Read the original article
Hit count: 224
We are facing the following problem in a Spring service, in a multi-threaded environment:
- three lists are freely and independently accessed for Read
- once in a while (every 5 minutes), they are all updated to new values. There are some dependencies between the lists, making that, for instance, the third one should not be read while the second one is being updated and the first one already has new values ; that would break the three lists consistency.
My initial idea is to make a container object having the three lists as properties.
Then the synchronization would be first on that object, then one by one on each of the three lists.
Some code is worth a thousands words... so here is a draft
private class Sync {
final List<Something> a = Collections.synchronizedList(new ArrayList<Something>());
final List<Something> b = Collections.synchronizedList(new ArrayList<Something>());
final List<Something> c = Collections.synchronizedList(new ArrayList<Something>());
}
private Sync _sync = new Sync();
...
void updateRunOnceEveryFiveMinutes() {
final List<Something> newa = new ArrayList<Something>();
final List<Something> newb = new ArrayList<Something>();
final List<Something> newc = new ArrayList<Something>();
...building newa, newb and newc...
synchronized(_sync) {
synchronized(_sync.a) {
_synch.a.clear();
_synch.a.addAll(newa);
}
synchronized(_sync.b) { ...same with newb... }
synchronized(_sync.c) { ...same with newc... }
}
// Next is accessed by clients
public List<Something> getListA() {
return _sync.a;
}
public List<Something> getListB() { ...same with b... }
public List<Something> getListC() { ...same with c... }
The question would be,
- is this draft safe (no deadlock, data consistency)?
- would you have a better implementation suggestion for that specific problem?
update
Changed the order of _sync synchronization and newa... building.
Thanks
© Stack Overflow or respective owner