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

org.sfm.map.impl.MapperCache Maven / Gradle / Ivy

Go to download

Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.

There is a newer version: 1.10.3
Show newest version
package org.sfm.map.impl;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;

public final class MapperCache {

	@SuppressWarnings("unchecked")
	private final AtomicReference[]> mapperCache = new AtomicReference[]>(new CacheEntry[0]);
	
	private static final class CacheEntry {
		final K key;
		final M mapper;
		CacheEntry(final K key, final M mapper) {
			this.key = key;
			this.mapper = mapper;
		}

        @Override
        public String toString() {
            return "{" +  key +
                    "," + mapper +
                    '}';
        }
    }
	@SuppressWarnings("unchecked")
	public void add(final K key, final M mapper) {
		CacheEntry[] entries;
		CacheEntry[] newEntries;
		do {
			entries = mapperCache.get();

            for (CacheEntry entry : entries) {
                if (entry.key.equals(key)) {
                    // already added
                    return;
                }
            }
			
			newEntries = new CacheEntry[entries.length + 1];
			
			System.arraycopy(entries, 0, newEntries, 0, entries.length);
			newEntries[entries.length] = new CacheEntry(key, mapper);
		
		} while(!mapperCache.compareAndSet(entries, newEntries));
	}

	public M get(K key) {
		final CacheEntry[] entries = mapperCache.get();
        for (final CacheEntry entry : entries) {
            if (entry.key.equals(key)) {
                return entry.mapper;
            }
        }
		return null;
	}

    @Override
    public String toString() {
        return "MapperCache{" + Arrays.toString(mapperCache.get()) +
                '}';
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy