package com.mudalov.safe.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * API Entry point, links commands and execution contexts
 *
 * User: mudalov
 * Date: 22/01/15
 * Time: 23:57
 */
public class SafeCommands {

    private static final Logger log = LoggerFactory.getLogger(SafeCommands.class);

    private static final ReentrantLock groupContextLock = new ReentrantLock();

    private static final Map<String, GroupExecutionContext> groupContexts = new ConcurrentHashMap<String, GroupExecutionContext>();

    private static final String DefaultGroup = "DefaultGroup";

    private SafeCommands() {
    }

    public static <T> CommandRef<T> create(AbstractCommand<T> command, String group) {
        GroupExecutionContext groupContext = getGroupContext(group);
        command.setContext(groupContext);
        return new CommandRef<T>(groupContext, command);
    }

    public static <T> CommandRef<T> create(AbstractCommand<T> command) {
        return create(command, DefaultGroup);
    }

    private static GroupExecutionContext getGroupContext(String groupName) {
        GroupExecutionContext context = groupContexts.get(groupName);
        if (context != null) {
            return context;
        }
        groupContextLock.lock();
        try {
            context = groupContexts.get(groupName);
            if (context != null) {
                return context;
            }
            context = new GroupExecutionContext(groupName);
            groupContexts.put(groupName, context);
            return context;
        } finally {
            groupContextLock.unlock();
        }
    }

}

@@ -379,172 +379,22 @@
 nal 
-Logger log = LoggerFactory.getLogger(SafeCommands.class);%0A%0A    private static final ReentrantLock groupContextLock = new ReentrantLock();%0A%0A    private static final 
+ConcurrentHash
 Map%3C
@@ -1213,86 +1213,43 @@
     
-groupContextLock.lock();%0A        try %7B%0A            context = group
+context = new GroupExecution
 Context
-s.get
 (gro
@@ -1269,127 +1269,68 @@
     
-    if (context != null) %7B%0A                return context;%0A            %7D%0A            context = new GroupExecutionContex
+GroupExecutionContext prevContext = groupContexts.putIfAbsen
 t(gr
@@ -1328,32 +1328,41 @@
 Absent(groupName
+, context
 );%0A            g
@@ -1360,50 +1360,34 @@
     
-    groupContexts.put(groupName, context);
+if (prevContext == null) %7B
 %0A   
@@ -1425,15 +1425,12 @@
   %7D 
-finally
+else
  %7B%0A 
@@ -1444,33 +1444,26 @@
     
-groupContextLock.unlock()
+return prevContext
 ;%0A  

Remove unnecessary lock on context creation