aboutsummaryrefslogtreecommitdiffstats
path: root/vespaclient-core/src/main/java/com/yahoo/feedhandler/ThreadedFeedAccess.java
blob: 215ea6b9917b492207766d3765ffc2ccad55b007 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.feedhandler;

import com.yahoo.concurrent.ThreadFactoryFactory;
import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentRemove;
import com.yahoo.document.DocumentUpdate;
import com.yahoo.feedapi.SimpleFeedAccess;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

final class ThreadedFeedAccess implements SimpleFeedAccess {

    private final SimpleFeedAccess simpleFeedAccess;
    private final ExecutorService executorService;
    private final Executor executor;
    ThreadedFeedAccess(int numThreads, SimpleFeedAccess simpleFeedAccess) {
        this.simpleFeedAccess = simpleFeedAccess;
        if (numThreads <= 0) {
            numThreads = Runtime.getRuntime().availableProcessors();
        }
        if (numThreads > 1) {
            executorService = new ThreadPoolExecutor(numThreads, numThreads, 0L, TimeUnit.SECONDS,
                    new SynchronousQueue<>(false),
                    ThreadFactoryFactory.getDaemonThreadFactory("feeder"),
                    new ThreadPoolExecutor.CallerRunsPolicy());
            executor = executorService;
        } else {
            executorService = null;
            executor = new Executor() {
                @Override
                public void execute(Runnable command) {
                    command.run();
                }
            };
        }
    }

    @Override
    public void put(DocumentPut doc) {
        executor.execute(() -> simpleFeedAccess.put(doc));
    }

    @Override
    public void remove(DocumentRemove remove) {
        executor.execute(() -> simpleFeedAccess.remove(remove));
    }

    @Override
    public void update(DocumentUpdate update) {
        executor.execute(() -> simpleFeedAccess.update(update));
    }

    @Override
    public boolean isAborted() {
        return simpleFeedAccess.isAborted();
    }
    @Override
    public void close() {
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}