Skip to content

Instantly share code, notes, and snippets.

@whyvrafvr
Last active March 12, 2020 15:35
Show Gist options
  • Save whyvrafvr/0f80bc38e0a4da102cfb06c6420baf4a to your computer and use it in GitHub Desktop.
Save whyvrafvr/0f80bc38e0a4da102cfb06c6420baf4a to your computer and use it in GitHub Desktop.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fr.trendev.controllers;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.IMap;
import fr.trendev.controllers.qualifiers.HazelcastDistributedMap;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.ApplicationScoped;
/**
*
* @author jsie
*/
@ApplicationScoped
@HazelcastDistributedMap
public class HazelcastDistributedMapRecordsManager extends HazelcastAbstractRecordsManager {
private IMap<String, LinkedList<String>> map;
private static final Logger LOG = Logger.getLogger(HazelcastDistributedMapRecordsManager.class.getName());
public HazelcastDistributedMapRecordsManager() {
super();
String mapConfigName = this.getClass().getName();
MapConfig mc = hz.getConfig().getMapConfigOrNull(mapConfigName);
if (mc == null) {
mc = new MapConfig(mapConfigName)
.setBackupCount(MapConfig.MAX_BACKUP_COUNT);
hz.getConfig().addMapConfig(mc);
}
this.map = hz.getMap(mapConfigName);
}
@PostConstruct
@Override
public void init() {
super.init();
LOG.log(Level.WARNING, "{0} is now initialized", this.getClass().getSimpleName());
}
@PreDestroy
@Override
public void close() {
LOG.log(Level.WARNING, "Destroying {0}", this.getClass().getSimpleName());
}
@Override
public List<String> add(String value) {
LinkedList<String> records = new LinkedList<>();
// replace with FencedLock when CP system will be enabled
Lock hzLock = hz.getLock(this.getClass().getName());
hzLock.lock();
try {
records = this.map.getOrDefault(key, new LinkedList<>());
//pop old entries
if (records.size() >= maxSize) {
while (records.size() != maxSize - 1) {
records.remove();
}
}
records.add(value);
this.map.put(key, records);
} finally {
hzLock.unlock();
}
return Collections.unmodifiableList(records);
}
@Override
public String getType() {
return RecordsManagerProducer.HAZELCAST_DISTRIBUTED_MAP;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment