|
| 1 | +package v.o.i.d.worker; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | +import java.util.concurrent.Executor; |
| 7 | +import java.util.concurrent.ExecutorService; |
| 8 | +import java.util.concurrent.Executors; |
| 9 | +import java.util.concurrent.Future; |
| 10 | +import java.util.concurrent.atomic.AtomicInteger; |
| 11 | + |
| 12 | +import static v.o.i.d.worker.RandomWorkload.randomWork; |
| 13 | +import static v.o.i.d.worker.RandomWorkload.randomWorkList; |
| 14 | + |
| 15 | +public class WorkerExample2 { |
| 16 | + |
| 17 | + private static List<Integer> createQueueList() { |
| 18 | + return Collections.synchronizedList(new ArrayList<>()); |
| 19 | + } |
| 20 | + |
| 21 | + private static final Executor executor = Executors.newSingleThreadExecutor(); |
| 22 | + |
| 23 | + private static final AtomicInteger counterProcessed = new AtomicInteger(0); |
| 24 | + private static final AtomicInteger counterWork = new AtomicInteger(0); |
| 25 | + |
| 26 | + /** |
| 27 | + * This method is called by the scheduler. |
| 28 | + */ |
| 29 | + public static void runOneIteration() { |
| 30 | + try { |
| 31 | + List<Integer> orgIds = randomWorkList(); |
| 32 | + counterWork.addAndGet(orgIds.size()); |
| 33 | + |
| 34 | + process(orgIds); |
| 35 | + } catch (Exception e) { |
| 36 | + System.out.println("Top level service failure"); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static void queueForRebuild(int orgId) { |
| 41 | + process(Collections.singletonList(orgId)); |
| 42 | + counterWork.incrementAndGet(); |
| 43 | + } |
| 44 | + |
| 45 | + private static void process(List<Integer> orgIds) { |
| 46 | + if (orgIds.isEmpty()) { |
| 47 | + return; |
| 48 | + } |
| 49 | + executor.execute(() -> { |
| 50 | + for (Integer orgId : orgIds) { |
| 51 | + counterProcessed.incrementAndGet(); |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + public static void main(String[] args) { |
| 57 | + ExecutorService es = Executors.newCachedThreadPool(); |
| 58 | + List<Future<?>> futures = new ArrayList<>(); |
| 59 | + |
| 60 | + int i = 100000; |
| 61 | + while (i-- > 0) { |
| 62 | + futures.add(es.submit(WorkerExample::runOneIteration)); |
| 63 | + futures.add(es.submit(() -> queueForRebuild(randomWork()))); |
| 64 | + queueForRebuild(randomWork()); |
| 65 | + } |
| 66 | + |
| 67 | + futures.forEach(f -> { |
| 68 | + try { f.get();} catch (Exception ignore) {} |
| 69 | + }); |
| 70 | + System.out.println("Finished jobs: " + futures.size()); |
| 71 | + |
| 72 | + System.out.println("---"); |
| 73 | + System.out.println("Submitted: " + counterWork.get()); |
| 74 | + System.out.println("Processed: " + counterProcessed.get()); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments