org.sfm.map.impl.MapperCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of simpleFlatMapper Show documentation
Show all versions of simpleFlatMapper Show documentation
Java library to map flat record - ResultSet, csv - to java object with minimum configuration and low footprint.
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()) +
'}';
}
}