package com.duiba.tuia.youtui.web.tool;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import org.junit.Assert;
import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by wubo on 2017/6/23.
 */
public class CacheTest {

    private AtomicInteger loadTimes = new AtomicInteger(0);

    private long start = System.currentTimeMillis();

    private LoadingCache<Long, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(2,TimeUnit.SECONDS).expireAfterWrite(4, TimeUnit.SECONDS).build(new CacheLoader<Long, String>() {

        @Override
        public String load(Long key) throws Exception {
            String threadName = Thread.currentThread().getName();
            System.out.println("thread:" + threadName + " 开始load cache,time:" + (System.currentTimeMillis() - start));
            Thread.sleep(200);
            System.out.println("thread:"+ threadName +"  load ok!");
            loadTimes.addAndGet(1);
            return threadName;
        }
    });

    @Test
    public void test() throws InterruptedException {
        Runnable r = ()->{
            try {
                System.out.println(
                        Thread.currentThread().getName() + "  start,time:" + (System.currentTimeMillis() - start));
                System.out.println(Thread.currentThread().getName() + " get value = " + cache.get(1L) + ",time:" + (
                        System.currentTimeMillis() - start));
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        };

        for (int i = 0; i < 5; i++) {
            new Thread(r).start();
        }

        Thread.sleep(2500);

        new Thread(r).start();//触发 refreshAfterWrite,只有一个线程 load，其他线程返回旧值
        new Thread(r).start();//返回旧值

        Thread.sleep(4500);

        new Thread(r).start();//触发 expireAfterWrite,只有一个线程 load，其他线程等着load完成后返回新值
        new Thread(r).start();//返回新值

        Thread.sleep(1000);
    }


}
