1   package ch.qos.logback.classic.pattern;
2   
3   import static org.junit.Assert.assertEquals;
4   
5   import java.util.ArrayList;
6   import java.util.List;
7   import java.util.Random;
8   
9   import ch.qos.logback.classic.pattern.lru.Event;
10  import ch.qos.logback.classic.pattern.lru.T_LRUCache;
11  
12  public class Simulator {
13  
14    Random random;
15  
16    int worldSize;
17    int get2PutRatio;
18    boolean multiThreaded;
19  
20    public Simulator(int worldSize, int get2PutRatio, boolean multiThreaded) {
21      this.worldSize = worldSize;
22      this.get2PutRatio = get2PutRatio;
23      long seed = System.nanoTime();
24      // System.out.println("seed is "+seed);
25      random = new Random(seed);
26      this.multiThreaded = multiThreaded;
27    }
28  
29    public List<Event> generateScenario(int len) {
30      List<Event> scenario = new ArrayList<Event>();
31  
32      for (int i = 0; i < len; i++) {
33  
34        int r = random.nextInt(get2PutRatio);
35        boolean put = false;
36        if (r == 0) {
37          put = true;
38        }
39        r = random.nextInt(worldSize);
40        Event<String> e = new Event<String>(put, String.valueOf(r));
41        scenario.add(e);
42      }
43      return scenario;
44    }
45  
46    public void simulate(List<Event> scenario, LRUCache<String, String> lruCache,
47        T_LRUCache<String> tlruCache) {
48      for (Event<String> e : scenario) {
49        if (e.put) {
50          lruCache.put(e.k, e.k);
51          tlruCache.put(e.k);
52        } else {
53          @SuppressWarnings("unused")
54          String r0 = lruCache.get(e.k);
55          @SuppressWarnings("unused")
56          String r1 = tlruCache.get(e.k);
57          if (!multiThreaded) {
58            // if the simulation is used in a multi-threaded
59            // context, then the state of lruCache may be different than
60            // that of tlruCache. In single threaded mode, they should
61            // return the same values all the time
62            if (r0 != null) {
63              assertEquals(r0, e.k);
64            }
65            assertEquals(r0, r1);
66          }
67        }
68      }
69    }
70  
71    // void compareAndDumpIfDifferent(LRUCache<String, String> lruCache,
72    // T_LRUCache<String> tlruCache) {
73    // lruCache.dump();
74    // tlruCache.dump();
75    // if(!lruCache.keyList().equals(tlruCache.ketList())) {
76    // lruCache.dump();
77    // tlruCache.dump();
78    // throw new AssertionFailedError("s");
79    // }
80    // }
81  }