HiveBrain v1.2.0
Get Started
← Back to all entries
principlejavaMinor

Configurable synchronization approach in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
synchronizationconfigurableapproachjava

Problem

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 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();

        Properties properties = new Properties();
        properties.load(SyncFactory.class.getClassLoader().getResourceAsStream("lock.properties"));

        for (Map.Entry 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
    }
  }
}

Solution

I just don't see a point in this factory. It has nothing in common with locking except class name, getLock method and "lock.properties" string inside. It's just a global hash map.
You always can (should) use synchronized with this or even better with private ivar. Any need too use your factory makes me think there is a bad design.

Context

StackExchange Code Review Q#14290, answer score: 2

Revisions (0)

No revisions yet.