All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ibm.fhir.persistence.jdbc.cache.NameIdCache Maven / Gradle / Ivy

There is a newer version: 4.11.1
Show newest version
/*
 * (C) Copyright IBM Corp. 2020
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package com.ibm.fhir.persistence.jdbc.cache;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.ibm.fhir.persistence.jdbc.dao.api.INameIdCache;


/**
 * @param  the type of the identity value held by the cache
 */
public class NameIdCache implements INameIdCache {

    // We use LinkedHashMap for the local map because we also need to maintain order
    // of insertion to make sure we have correct LRU behavior when updating the shared cache
    private final ThreadLocal> local = new ThreadLocal<>();
    
    // The cache shared at the server level
    private final ConcurrentHashMap shared = new ConcurrentHashMap<>();
    
    /**
     * Public constructor
     */
    public NameIdCache() {
    }

    @Override
    public void updateSharedMaps() {
        
        Map localMap = local.get();
        if (localMap != null) {
            // no need to synchronize because we can use a ConcurrentHashMap
            shared.putAll(localMap);
            localMap.clear();
        }
    }
    
    @Override
    public T getId(String key) {
        T result = null;
        Map localMap = local.get();
        if (localMap != null) {
            result = localMap.get(key);
        }

        if (result == null) {
            result = shared.get(key);
        }
        return result;
    }

    @Override
    public void addEntry(String resourceType, T resourceTypeId) {
        Map localMap = local.get();
        if (localMap == null) {
            localMap = new HashMap<>();
            local.set(localMap);
        }
        localMap.put(resourceType, resourceTypeId);
    }

    @Override
    public void reset() {
        local.remove();
        shared.clear();
    }

    @Override
    public void clearLocalMaps() {
        Map map = local.get();
        if (map != null) {
            map.clear();
        }
    }

    @Override
    public void prefill(Map content) {
        // as the given content is supposed to be already committed in the database,
        // we can add it directly to the shared map
        this.shared.putAll(content);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy