Kenmegne
7 days ago 23a46b4be35277e06ec89f48730eeb694e686be8
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.megatim.fdxconsultation.core.impl.dataproductionworker;
 
import com.megatim.fdxconsultation.model.dataproduction.DataProduction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
 
/**
 *
 * @author Gabuntu
 */
@ApplicationScoped
public class DefaultDataProductionWorkerGroup implements DataProductionWorkerGroup {
 
    @Inject
    private DataProductionTaskFactory dataProductionTaskFactory;
 
    private final int WORKER_NUMBER = 4;
    private final DataProductionWorker[] workers = new DataProductionWorker[WORKER_NUMBER];
    private final Map<Integer, Set<String>> workerToCodeTypeFichiers = new HashMap<>();
    private final AtomicInteger currentWorkerIndex = new AtomicInteger(0);
 
    @Override
    public void start() {
        for (int i = 0; i < WORKER_NUMBER; i++) {
            workers[i] = new DataProductionWorker("Worker-" + i);
            workers[i].start();
            workerToCodeTypeFichiers.put(i, new HashSet<>());
        }
    }
 
    @Override
    public void shutdown() {
        for (DataProductionWorker worker : workers) {
            worker.shutdown();
        }
        workerToCodeTypeFichiers.clear();
    }
 
    @Override
    public void addNewDataProductionTask(DataProduction dataProduction) {
        DataProductionWorker worker = workerForTask(dataProduction.getCodeTypeFichier());
        worker.addTask(dataProductionTaskFactory.createDataProductionTask(dataProduction));
    }
 
    private synchronized DataProductionWorker workerForTask(String codeTypeFichier) {
        Integer workerIndex = workerLinkToCodeTypeFichier(codeTypeFichier);
        if (workerIndex != null) {
            return workers[workerIndex];
        }
        int currentIndex = currentWorkerIndex.getAndIncrement();
        DataProductionWorker worker = workers[currentIndex];
 
        workerToCodeTypeFichiers.get(currentIndex).add(codeTypeFichier);
 
        changeCurrentWorkerIndex();
 
        return worker;
    }
 
    private Integer workerLinkToCodeTypeFichier(String codeTypeFichier) {
        return workerToCodeTypeFichiers
                .entrySet()
                .stream()
                .filter(e -> e.getValue().contains(codeTypeFichier))
                .findFirst()
                .map(e -> e.getKey())
                .orElse(null);
    }
 
    private void changeCurrentWorkerIndex() {
        if ((currentWorkerIndex.get() % (WORKER_NUMBER - 1)) == 0) {
            currentWorkerIndex.set(0);
        }
    }
 
}