jhalterman / expiringmap

A high performance thread-safe map that expires entries
Apache License 2.0
1k stars 142 forks source link

Is it really thread safe?! it behaves differently than ConcurrentHahMap. please run code below. #75

Open abprojects055 opened 2 years ago

abprojects055 commented 2 years ago
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {
        Data data = new Data();
        ExecutorService service = Executors.newFixedThreadPool(5);

        IntStream.range(0, 1000)
                .forEach(count -> service.submit(data::incrementBy));

    }

    public static class Data {

        private Map<Integer, Integer> map;

        public Data() {
//        this.map = new ConcurrentHashMap<>();
            this.map = ExpiringMap.builder()
                    .expiration(100, TimeUnit.MINUTES)
                    .expirationPolicy(ExpirationPolicy.CREATED).build();
            this.map.put(1, 0);
        }

        public void incrementBy() {
            this.map.computeIfPresent(1, (key, old) -> {
                System.out.println(old + 1);
                return old + 1;
            });
        }
    }
}