<commit_before>/* 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 org.flowable.job.service.impl.asyncexecutor;

import java.util.concurrent.RejectedExecutionException;

import org.flowable.common.engine.api.async.AsyncTaskExecutor;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.impl.async.DefaultAsyncTaskExecutor;
import org.flowable.common.engine.impl.cfg.TransactionPropagation;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandConfig;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.job.api.JobInfo;
import org.flowable.job.service.event.impl.FlowableJobEventBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <NAME>
 * @author <NAME>
 */
public class DefaultAsyncJobExecutor extends AbstractAsyncExecutor {

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

    /**
     * Thread responsible for async job acquisition.
     */
    protected Thread asyncJobAcquisitionThread;

    /**
     * Thread responsible for timer job acquisition.
     */
    protected Thread timerJobAcquisitionThread;

    /**
     * Thread responsible for resetting the expired jobs.
     */
    protected Thread resetExpiredJobThread;

    /**
     * The async task executor used for job execution.
     */
    protected AsyncTaskExecutor taskExecutor;
    protected boolean shutdownTaskExecutor;

    public DefaultAsyncJobExecutor() {
        super();
    }

    public DefaultAsyncJobExecutor(AsyncJobExecutorConfiguration configuration) {
        super(configuration);
    }

    @Override
    protected boolean executeAsyncJob(final JobInfo job, Runnable runnable) {
        try {
            taskExecutor.execute(runnable);
            return true;

        } catch (RejectedExecutionException e) {
            sendRejectedEvent(job);
            unacquireJobAfterRejection(job);

            // Job queue full, returning false so (if wanted) the acquiring can be throttled
            return false;
        }
    }

    protected void sendRejectedEvent(JobInfo job) {
        FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
        if (eventDispatcher != null && eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
                FlowableEngineEventType.JOB_REJECTED, job), jobServiceConfiguration.getEngineName());
        }
    }

    protected void unacquireJobAfterRejection(final JobInfo job) {

        // When a RejectedExecutionException is caught, this means that the
        // queue for holding the jobs that are to be executed is full and can't store more.
        // The job is now 'unlocked', meaning that the lock owner/time is set to null,
        // so other executors can pick the job up (or this async executor, the next time the
        // acquire query is executed.

        CommandConfig commandConfig = new CommandConfig(false, TransactionPropagation.REQUIRES_NEW);
        jobServiceConfiguration.getCommandExecutor().execute(commandConfig, new Command<Void>() {
            @Override
            public Void execute(CommandContext commandContext) {
                jobServiceConfiguration.getJobManager().unacquire(job);
                return null;
            }
        });
    }

    @Override
    protected void startAdditionalComponents() {
        if (!isMessageQueueMode) {
            initAsyncJobExecutionThreadPool();
            startJobAcquisitionThread();
        }

        if (configuration.isUnlockOwnedJobs()) {
            unlockOwnedJobs();
        }

        if (configuration.isTimerRunnableNeeded()) {
            startTimerAcquisitionThread();
        }
        startResetExpiredJobsThread();
    }

    @Override
    protected void shutdownAdditionalComponents() {
        stopResetExpiredJobsThread();
        stopTimerAcquisitionThread();
        stopJobAcquisitionThread();
        stopExecutingAsyncJobs();

        if (configuration.isUnlockOwnedJobs()) {
            unlockOwnedJobs();
        }
<commit_msg>Own jobs should be unlocked before starting the job acquisition threads<commit_after>/* 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 org.flowable.job.service.impl.asyncexecutor;

import java.util.concurrent.RejectedExecutionException;

import org.flowable.common.engine.api.async.AsyncTaskExecutor;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher;
import org.flowable.common.engine.impl.async.DefaultAsyncTaskExecutor;
import org.flowable.common.engine.impl.cfg.TransactionPropagation;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandConfig;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.job.api.JobInfo;
import org.flowable.job.service.event.impl.FlowableJobEventBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <NAME>
 * @author <NAME>
 */
public class DefaultAsyncJobExecutor extends AbstractAsyncExecutor {

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

    /**
     * Thread responsible for async job acquisition.
     */
    protected Thread asyncJobAcquisitionThread;

    /**
     * Thread responsible for timer job acquisition.
     */
    protected Thread timerJobAcquisitionThread;

    /**
     * Thread responsible for resetting the expired jobs.
     */
    protected Thread resetExpiredJobThread;

    /**
     * The async task executor used for job execution.
     */
    protected AsyncTaskExecutor taskExecutor;
    protected boolean shutdownTaskExecutor;

    public DefaultAsyncJobExecutor() {
        super();
    }

    public DefaultAsyncJobExecutor(AsyncJobExecutorConfiguration configuration) {
        super(configuration);
    }

    @Override
    protected boolean executeAsyncJob(final JobInfo job, Runnable runnable) {
        try {
            taskExecutor.execute(runnable);
            return true;

        } catch (RejectedExecutionException e) {
            sendRejectedEvent(job);
            unacquireJobAfterRejection(job);

            // Job queue full, returning false so (if wanted) the acquiring can be throttled
            return false;
        }
    }

    protected void sendRejectedEvent(JobInfo job) {
        FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
        if (eventDispatcher != null && eventDispatcher.isEnabled()) {
            eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(
                FlowableEngineEventType.JOB_REJECTED, job), jobServiceConfiguration.getEngineName());
        }
    }

    protected void unacquireJobAfterRejection(final JobInfo job) {

        // When a RejectedExecutionException is caught, this means that the
        // queue for holding the jobs that are to be executed is full and can't store more.
        // The job is now 'unlocked', meaning that the lock owner/time is set to null,
        // so other executors can pick the job up (or this async executor, the next time the
        // acquire query is executed.

        CommandConfig commandConfig = new CommandConfig(false, TransactionPropagation.REQUIRES_NEW);
        jobServiceConfiguration.getCommandExecutor().execute(commandConfig, new Command<Void>() {
            @Override
            public Void execute(CommandContext commandContext) {
                jobServiceConfiguration.getJobManager().unacquire(job);
                return null;
            }
        });
    }

    @Override
    protected void startAdditionalComponents() {
        if (configuration.isUnlockOwnedJobs()) {
            unlockOwnedJobs();
        }

        if (!isMessageQueueMode) {
            initAsyncJobExecutionThreadPool();
            startJobAcquisitionThread();
        }

        if (configuration.isTimerRunnableNeeded()) {
            startTimerAcquisitionThread();
        }
        startResetExpiredJobsThread();
    }

    @Override
    protected void shutdownAdditionalComponents() {
        stopResetExpiredJobsThread();
        stopTimerAcquisitionThread();
        stopJobAcquisitionThread();
        stopExecutingAsyncJobs();

        if (configuration.isUnlockOwnedJobs()) {
            unlockOwnedJobs();
        }

{'fraction_non_alphanumeric': 0.0783705541770058, 'fraction_numerical': 0.0012406947890818859, 'mean_word_length': 3.103945693678405, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, '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': '6822416', 'n_tokens_mistral': 2482, 'n_tokens_neox': 2380, 'n_words': 658}