package com.demo.map;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import static java.lang.Thread.sleep;
public class MyRedis {
private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
public static void main(String[] args) throws InterruptedException {
Redis redis = Redis.getInstance();
for (int i = 0; i < 10; i++) {
new Thread(()->{
for (int j = 0; j < 100; j++) {
redis.set("key"+j,"value"+j);
}
}).start();
}
sleep(1000);
System.out.println(redis.getMap().size());
}
}
class Redis{
private final Map<String,RedisValue<String>> map = new ConcurrentHashMap<>();
private static final int DEFAULT_EXPIRE_TIME = 1000;
private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10, r -> {
Thread thread = new Thread(r);
thread.setName("schedule-thread" + thread.getId());
return thread;
});
private static final Redis redis = new Redis();
private Redis(){
scheduledExecutorService.scheduleWithFixedDelay(()->{
long now = System.currentTimeMillis();
map.entrySet().removeIf(entry -> now > entry.getValue().getExpireTime());
},0,100, TimeUnit.MILLISECONDS);
}
public static Redis getInstance(){
return redis;
}
public void set(String key,String value){
RedisValue<String> redisValue = new RedisValue<String>(value, System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
map.put(key,redisValue);
}
public String get(String key){
return map.get(key)==null?
null: map.get(key).getValue();
}
public Map getMap(){
return map;
}
}
class RedisValue<T>{
private final T value;
private final long expireTime;
public RedisValue(T value,long expireTime){
this.value = value;
this.expireTime = expireTime;
}
public T getValue(){
return value;
}
public long getExpireTime(){
return expireTime;
}
}