/*
 * Copyright (c) 2008-2014 Maxifier Ltd. All Rights Reserved.
 */
package com.maxifier.mxcache.impl.resource;

import com.maxifier.mxcache.CacheFactory;
import com.maxifier.mxcache.config.ResourceConfig;
import com.maxifier.mxcache.resource.MxResource;
import gnu.trove.map.hash.THashMap;
import gnu.trove.set.hash.THashSet;

import javax.annotation.Nonnull;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

/**
 * @author Alexander Kochurov (alexander.kochurov@maxifier.com)
 */
public final class MxResourceFactory {
    private static final Map<String, MxResource> RESOURCES = new THashMap<String, MxResource>();

    static {
        for (ResourceConfig resourceConfig : CacheFactory.getConfiguration().getResources()) {
            String name = resourceConfig.getName();
            RESOURCES.put(name, new MxStaticResource(name));
        }
    }

    private MxResourceFactory() {
    }

    /**
     * It is guaranteed that this method will always return the same object for a single id.
     * I.e. resources are singletons.
     * Use @{link #createResource(Object,String)} to create non-singleton resources.
     *
     * @param id resource name
     *
     * @return resource with given name
     */
    public static synchronized MxResource getResource(@Nonnull String id) {
        MxResource resource = RESOURCES.get(id);
        if (resource == null) {
            resource = new MxStaticResource(id);
            RESOURCES.put(id, resource);
        }
        return resource;
    }

    public static MxResource createResource(@Nonnull Object owner, @Nonnull String id) {
        return new MxBoundResource(owner, id);
    }

    public static synchronized Set<MxResource> getAllResources() {
        return Collections.unmodifiableSet(new THashSet<MxResource>(RESOURCES.values()));
    }
}

@@ -261,45 +261,8 @@
 e;%0D%0A
-import gnu.trove.map.hash.THashMap;%0D%0A
 impo
@@ -294,16 +294,16 @@
 shSet;%0D%0A
+
 %0D%0Aimport
@@ -406,16 +406,64 @@
 il.Set;%0D
+%0Aimport java.util.concurrent.ConcurrentHashMap;%0D
 %0A%0D%0A/**%0D%0A
@@ -597,16 +597,30 @@
 c final 
+ConcurrentHash
 Map%3CStri
@@ -647,25 +647,34 @@
 URCES = new 
-T
+Concurrent
 HashMap%3CStri
@@ -1328,29 +1328,16 @@
  static 
-synchronized 
 MxResour
@@ -1510,32 +1510,57 @@
 d);%0D%0A           
+ MxResource oldResource =
  RESOURCES.put(i
@@ -1557,16 +1557,24 @@
 RCES.put
+IfAbsent
 (id, res
@@ -1578,24 +1578,120 @@
 resource);%0D%0A
+            if (oldResource != null) %7B%0D%0A                resource = oldResource;%0D%0A            %7D%0D%0A
         %7D%0D%0A 

Remove synchronized from MxResourceFactory#getResource