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

com.ibm.icu.impl.SimpleCache Maven / Gradle / Ivy

Go to download

International Component for Unicode for Java (ICU4J) is a mature, widely used Java library providing Unicode and Globalization support

The newest version!
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
 ****************************************************************************
 * Copyright (c) 2007-2015 International Business Machines Corporation and  *
 * others.  All rights reserved.                                            *
 ****************************************************************************
 */

package com.ibm.icu.impl;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SimpleCache implements ICUCache {
    private static final int DEFAULT_CAPACITY = 16;

    private volatile Reference> cacheRef = null;
    private int type = ICUCache.SOFT;
    private int capacity = DEFAULT_CAPACITY;

    public SimpleCache() {
    }

    public SimpleCache(int cacheType) {
        this(cacheType, DEFAULT_CAPACITY);
    }

    public SimpleCache(int cacheType, int initialCapacity) {
        if (cacheType == ICUCache.WEAK) {
            type = cacheType;
        }
        if (initialCapacity > 0) {
            capacity = initialCapacity;
        }
    }

    @Override
    public V get(Object key) {
        Reference> ref = cacheRef;
        if (ref != null) {
            Map map = ref.get();
            if (map != null) {
                return map.get(key);
            }
        }
        return null;
    }

    @Override
    public void put(K key, V value) {
        Reference> ref = cacheRef;
        Map map = null;
        if (ref != null) {
            map = ref.get();
        }
        if (map == null) {
            map = Collections.synchronizedMap(new HashMap(capacity));
            if (type == ICUCache.WEAK) {
                ref = new WeakReference>(map);
            } else {
                ref = new SoftReference>(map);
            }
            cacheRef = ref;
        }
        map.put(key, value);
    }

    @Override
    public void clear() {
        cacheRef = null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy