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

io.polaris.core.cache.MapCache Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package io.polaris.core.cache;

import io.polaris.core.map.Maps;
import io.polaris.core.tuple.Ref;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * @author Qt
 * @since 1.8
 */
public class MapCache implements ICache {

	private final Map> map;

	public MapCache() {
		this.map = new ConcurrentHashMap<>();
	}

	public MapCache(int maxCapacity) {
		if (maxCapacity > 0) {
			this.map = Collections.synchronizedMap(Maps.newLimitCapacityMap(maxCapacity));
		} else {
			this.map = new ConcurrentHashMap<>();
		}
	}

	public MapCache(int maxCapacity, boolean accessOrder) {
		if (maxCapacity > 0) {
			this.map = Collections.synchronizedMap(Maps.newLimitCapacityMap(maxCapacity, accessOrder));
		} else {
			this.map = new ConcurrentHashMap<>();
		}
	}

	public MapCache(Map> map) {
		this.map = map;
	}

	@Nullable
	@Override
	public Ref get(@Nonnull K key) {
		return map.get(key);
	}

	@Nullable
	@Override
	public V getIfPresent(@Nonnull K key) {
		Ref ref = map.get(key);
		return ref == null ? null : ref.get();
	}

	@Nullable
	@Override
	public V get(@Nonnull K key, Supplier loader) {
		Ref ref = map.get(key);
		return ref == null ? loader.get() : ref.get(loader);
	}

	@Override
	public Ref putIfAbsent(@Nonnull K key, @Nullable V value) {
		return map.putIfAbsent(key, Ref.of(value));
	}

	@Override
	public void put(@Nonnull K key, @Nullable V value) {
		map.put(key, Ref.of(value));
	}

	@Override
	public void putAll(Map m) {
		m.forEach((k, v) -> map.put(k, Ref.of(v)));
	}

	@Override
	public void remove(K key) {
		map.remove(key);
	}

	@Override
	public void clear() {
		map.clear();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy