How to make a simultaneous hash map streaming security with receiving and placing as an atomic operation?

Is my method safe below? This method is in the Singleton class.

private static final Map<String, PreparedStatement> holder = new ConcurrentHashMap<>(); public BoundStatement getStatement(String cql) { Session session = TestUtils.getInstance().getSession(); PreparedStatement ps = holder.get(cql); if(ps == null) { // If "ps" is already present in cache, then we don't have to synchronize and make threads wait. synchronized { ps = holder.get(cql); if (ps == null) { ps = session.prepare(cql); holder.put(cql, ps); } } } return ps.bind(); } 

I work with Cassandra and use the datastax java driver, so I reuse prepared statements and why I cache it here. Prepared Report and BoundStatement .

Is there a better way to make a getStatement method getStatement thread safe (if it is thread safe) instead of using a synchronized block? Any other data structure that might be thread safe for such operations? I am working with Java 7.

+1
source share
2 answers

Since .putIfAbsent is in Java7, you can use it:

  private static final ConcurrentHashMap<String, PreparedStatement> holder = new ConcurrentHashMap<>(); public BoundStatement getStatement(String cql) { Session session = TestUtils.getInstance().getSession(); PreparedStatement ps = holder.get(cql); if(ps == null) { // If "ps" is already present in cache, then we don't have to synchronize and make threads wait. if (holder.putIfAbsent(cql, session.prepare(cql)) != null) { // Someone else got there before, handle } } return ps.bind(); } 

Note that putIfAbsent still uses internal synchronization.

+1
source

If you want to do some form of memoization, then this is the best / easiest thing you can do in Java 7. Guava has a caching implementation for computing, and Java 8 has a computeIfAbsent method in Map , but you're clearly out of luck.

If you can create objects on an empty race, as Alexey says, this would be the best solution. If you do not, your implementation will be both thread-safe and reasonable.

This is a double-check lock form, however with this implementation you guarantee that this will happen before ordering using the put and get methods for CHM.

+1
source

Source: https://habr.com/ru/post/888072/


All Articles