I am interested in the community opinion about the following approach for the synchronization. Generally it is based on the idea to have a configurable way to apply locking on some logic parts.
Any comments and review is appreciated :) .
lock.properties
keeps configuration:
foo=true
bar=false
SynFactory.java
produces locks:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class SyncFactory {
private static HashMap<String, Object> locks = null;
public static synchronized Object getLock(String key) {
init();
return locks.containsKey(key) ? locks.get(key) : new Object();
}
private static void init() {
if (locks == null) {
try {
locks = new HashMap<String, Object>();
Properties properties = new Properties();
properties.load(SyncFactory.class.getClassLoader().getResourceAsStream("lock.properties"));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
// key=true => locking with ine object
// key=false => lock object should always be new
if (Boolean.parseBoolean(String.valueOf(entry.getValue()))) {
locks.put((String) entry.getKey(), new Object());
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Service.java
actual usage:
public class Service {
public void foo() {
synchronized (SyncFactory.getLock("foo")) {
// do some logic
}
}
public void bar() {
synchronized (SyncFactory.getLock("bar")) {
// do some logic
}
}
}