<commit_before>/*
 * Copyright 2016 Crown Copyright
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package stroom.search.server.taskqueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.task.server.StroomThreadGroup;
import stroom.util.spring.StroomShutdown;
import stroom.util.thread.CustomThreadFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TaskExecutor {
    private static final int DEFAULT_MAX_THREADS = 5;

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);

    private volatile int maxThreads = DEFAULT_MAX_THREADS;

    private final AtomicInteger totalThreads = new AtomicInteger();

    private final ConcurrentSkipListSet<TaskProducer> producers = new ConcurrentSkipListSet<>();
    private final AtomicReference<TaskProducer> lastProducer = new AtomicReference<>();

    private final ReentrantLock taskLock = new ReentrantLock();
    private final Condition condition = taskLock.newCondition();

    private final ExecutorService executor;
    private volatile boolean running = true;

    public TaskExecutor(final String name) {
        final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name);
        final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5);
        executor = Executors.newSingleThreadExecutor(threadFactory);

        executor.execute(() -> {
            while (running) {
                taskLock.lock();
                try {
                    Runnable task = execNextTask();
                    if (task == null) {
                        condition.await();
                    }
                } catch (final InterruptedException e) {
                    // Clear the interrupt state.
                    Thread.interrupted();
                } catch (final RuntimeException e) {
                    LOGGER.error(e.getMessage(), e);
                } finally {
                    taskLock.unlock();
                }
            }
        });
    }

    @StroomShutdown
    public void stop() {
        running = false;
        // Wake up any waiting threads.
        signalAll();
        executor.shutdown();
    }<commit_msg>Now only starts the executor when started by lifecycle<commit_after>/*
 * Copyright 2016 Crown Copyright
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package stroom.search.server.taskqueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import stroom.task.server.StroomThreadGroup;
import stroom.util.spring.StroomShutdown;
import stroom.util.spring.StroomStartup;
import stroom.util.thread.CustomThreadFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TaskExecutor {
    private static final int DEFAULT_MAX_THREADS = 5;

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutor.class);

    private volatile int maxThreads = DEFAULT_MAX_THREADS;

    private final AtomicInteger totalThreads = new AtomicInteger();

    private final ConcurrentSkipListSet<TaskProducer> producers = new ConcurrentSkipListSet<>();
    private final AtomicReference<TaskProducer> lastProducer = new AtomicReference<>();

    private final ReentrantLock taskLock = new ReentrantLock();
    private final Condition condition = taskLock.newCondition();

    private final String name;
    private volatile ExecutorService executor;
    private volatile boolean running;

    public TaskExecutor(final String name) {
        this.name = name;
    }

    @StroomStartup
    public synchronized void start() {
        if (!running) {
            running = true;

            final ThreadGroup poolThreadGroup = new ThreadGroup(StroomThreadGroup.instance(), name);
            final CustomThreadFactory threadFactory = new CustomThreadFactory(name, poolThreadGroup, 5);
            executor = Executors.newSingleThreadExecutor(threadFactory);
            executor.execute(() -> {
                while (running) {
                    taskLock.lock();
                    try {
                        Runnable task = execNextTask();
                        if (task == null) {
                            condition.await();
                        }
                    } catch (final InterruptedException e) {
                        // Clear the interrupt state.
                        Thread.interrupted();
                    } catch (final RuntimeException e) {
                        LOGGER.error(e.getMessage(), e);
                    } finally {
                        taskLock.unlock();
                    }
                }
            });
        }
    }

    @StroomShutdown
    public synchronized void stop() {
        if (running) {
            running = false;
            // Wake up any waiting threads.
            signalAll();
            executor.shutdown();
        }
    }
{'fraction_non_alphanumeric': 0.07926084300549786, 'fraction_numerical': 0.0036652412950519244, 'mean_word_length': 2.602310231023102, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7662635', 'n_tokens_mistral': 1642, 'n_tokens_neox': 1570, 'n_words': 487}