8.4.15

Eh CacheManager for Unit Test

    static final String EHCACHE_CONFIG_TEMPLATE =
            "" + "";
    
    @Test
    public void testMulti() throws Exception {
        final CyclicBarrier barrier = new CyclicBarrier(11);
        final AtomicInteger ai = new AtomicInteger();
        final AtomicInteger ai2 = new AtomicInteger();
        
        Runnable r = new Runnable() {
            
            @Override
            public void run() {
                try {
                    testCacheManager(barrier, ai, ai2);
                } catch (InterruptedException | BrokenBarrierException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        
        ExecutorService pool = Executors.newCachedThreadPool();
        
        for(int i=0; i<10; ++i) {
            pool.execute(r);
        }
        
        barrier.await();
        
        pool.shutdown();
        assertTrue(pool.awaitTermination(1, TimeUnit.MINUTES));
        assertEquals(10, ai.get());
        assertEquals(55, ai2.get());
        
    }

    void testCacheManager(CyclicBarrier barrier, AtomicInteger ai, AtomicInteger ai2) throws InterruptedException, BrokenBarrierException {
        String threadName = Thread.currentThread().getName();
        String cacheManagerName = "CM-" + threadName;
        
        String configContent = String.format(EHCACHE_CONFIG_TEMPLATE, cacheManagerName);
        ReaderInputStream configStream = new ReaderInputStream(new StringReader(configContent ));
        CacheManager cacheManager = CacheManager.newInstance(configStream);
        
        Cache testCache = new Cache(
                new CacheConfiguration("testCache", 123)
                  .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
                  .eternal(false)
                  .timeToLiveSeconds(60)
                  .timeToIdleSeconds(30)
                  .diskExpiryThreadIntervalSeconds(0)
                  .persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP)));
        
        barrier.await();
        
        System.err.println(Thread.currentThread().getName() + ": CM " + String.valueOf(cacheManager));
        
        assertNull(cacheManager.getCache("testCache"));
        cacheManager.addCache(testCache);
        
        Integer v = ai.incrementAndGet();
        Element e = new Element("i", v);
        
        testCache.put(e);
        
        assertEquals(v, (Integer)cacheManager.getCache("testCache").get("i").getObjectValue());
        
        while(true) {
            int x = ai2.get();
            if(ai2.compareAndSet(x, x + v)) {
                System.err.printf("%s : X => (%d, %d)\n", threadName, x, v);
                break;
            }
        }
        
        cacheManager.shutdown();
    }

No comments: