mirror of https://github.com/micromata/borgbackup-butler.git

Kai Reinhard
11.05.2019 725b302f0272875f961b132e9c963378c11e8365
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package de.micromata.borgbutler.server.logging;
 
import org.junit.Assert;
import org.junit.jupiter.api.Test;
 
import java.util.ArrayList;
 
public class FiFoBufferTest {
    private FiFoBuffer<Long> fiFoBuffer;
    private Long counter = 0L;
    private ArrayList<Thread> threads = new ArrayList<>();
 
    @Test
    void test() {
        fiFoBuffer = new FiFoBuffer<>(1000);
        for (int i = 0; i < 10; i++) {
            startProducerThread();
            startConsumerThread(i % 2 == 0);
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException ex) {
 
            }
        }
        Assert.assertEquals(100000, counter.longValue());
    }
 
    private void startProducerThread() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    long value;
                    synchronized (threads) {
                        value = ++counter;
                    }
                    fiFoBuffer.add(value);
                }
            }
        };
        thread.start();
        threads.add(thread);
    }
 
    private void startConsumerThread(boolean ascending) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    if (ascending) {
                        for (int j = 0; j < fiFoBuffer.getSize(); j++) {
                            fiFoBuffer.get(j);
                        }
                    } else {
                        for (int j = fiFoBuffer.getSize(); j >= 0; j--) {
                            fiFoBuffer.get(j);
                        }
                    }
                }
            }
        };
        thread.start();
        threads.add(thread);
    }
}