Ellena557 / LRU-cache

0 stars 0 forks source link

There's the way to pass this test #1

Open irenkamalova opened 2 years ago

irenkamalova commented 2 years ago

https://github.com/Ellena557/LRU-cache/blob/e4baeccd54a7334dcc8cdeb33e95fe8e396a47a8/lru-cache/src/test/java/ru/ellen/SingleThreadCacheTest.java#L58

Look how you can make this test to be passed by every run :)

    @Test
    public void multipleThreadTest() {

        ArrayList<Integer> sizes = new ArrayList<>();

        boolean cacheIsOk = true;
        boolean containsGreater = false;
        // Запускаем 100 раз, увеличивая случайность
        for (int i = 0; i < 99; i++) {
            lruCache = new SingleThreadCache(3);
            ExecutorService service = Executors.newFixedThreadPool(10);
            for (int j = 0; j < 10; j++) {
                service.execute(new CachePutter());
            }
            service.shutdown();

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            sizes.add(lruCache.getCache().size());
            cacheIsOk = cacheIsOk && sizes.stream().allMatch(el -> el == 3);
            containsGreater = containsGreater || sizes.stream().anyMatch(el -> el > 3);
        }

        Assert.assertFalse(cacheIsOk);
        Assert.assertTrue(containsGreater);
    }
Ellena557 commented 2 years ago

But why do we need it?

In these three lines:

sizes.add(lruCache.getCache().size());
cacheIsOk = cacheIsOk && sizes.stream().allMatch(el -> el == 3);
containsGreater = containsGreater || sizes.stream().anyMatch(el -> el > 3);

We every time (100 times) add only one new value to array "sizes". And in the second line we will check the same condition for array "sizes" to which we will add only one new element. It seems to me that this kind of check will be a little bit redundant (the result is the same but we make 100 similar checks instead of one check in the end).