<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.activiti.engine.test.concurrency;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.activiti.engine.impl.history.HistoryLevel;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.apache.ibatis.exceptions.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Test that uses a number of threads to start processes and complete tasks concurrently.
 * 
 * @author <NAME>
 */
public class ConcurrentEngineUsageTest extends PluggableActivitiTestCase {

  private static Logger log = LoggerFactory.getLogger(ConcurrentEngineUsageTest.class);
  private static final int MAX_RETRIES = 5;
  
  @Deployment
  public void testConcurrentUsage() throws Exception {
    
    if(!processEngineConfiguration.getDatabaseType().equals("h2")) {
      int numberOfThreads = 5;
      int numberOfProcessesPerThread = 5;
      int totalNumberOfTasks = 2 * numberOfThreads * numberOfProcessesPerThread;
      
      ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(numberOfThreads));
      
      for(int i=0; i< numberOfThreads; i++) {
        executor.execute(new ConcurrentProcessRunnerRunnable(numberOfProcessesPerThread, "kermit" + i));
      }
      
      // Wait for termination or timeout and check if all tasks are complete
      executor.shutdown();
      executor.awaitTermination(20000, TimeUnit.MILLISECONDS);
      assertEquals(0, executor.getActiveCount());
      
      // Check there are no processes active anymore
      assertEquals(0, runtimeService.createProcessInstanceQuery().count());
      
      if(processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
        // Check if all processes and tasks are complete
        assertEquals(numberOfProcessesPerThread * numberOfThreads, historyService.createHistoricProcessInstanceQuery()
                .finished().count());
        assertEquals(totalNumberOfTasks, historyService.createHistoricTaskInstanceQuery()
                .finished().count());
      }
    }
  }
  
  protected void retryStartProcess(String runningUser) {
    int retries = MAX_RETRIES;
    int timeout = 200;
    boolean success = false;
    while(retries > 0 && !success) {
      try {
        runtimeService.startProcessInstanceByKey("concurrentProcess", Collections.singletonMap("assignee", (Object)runningUser));
        success = true;
      } catch(PersistenceException pe) {
        retries = retries - 1;
        log.debug("Retrying process start - " + (MAX_RETRIES - retries));
        try {
          Thread.sleep(timeout);<commit_msg>Forcing termination of pool when timeout is reached in concurrency test<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.activiti.engine.test.concurrency;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.activiti.engine.impl.history.HistoryLevel;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.test.PluggableActivitiTestCase;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.apache.ibatis.exceptions.PersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Test that uses a number of threads to start processes and complete tasks concurrently.
 * 
 * @author <NAME>
 */
public class ConcurrentEngineUsageTest extends PluggableActivitiTestCase {

  private static Logger log = LoggerFactory.getLogger(ConcurrentEngineUsageTest.class);
  private static final int MAX_RETRIES = 5;
  
  @Deployment
  public void testConcurrentUsage() throws Exception {
    
    if(!processEngineConfiguration.getDatabaseType().equals("h2")) {
      int numberOfThreads = 5;
      int numberOfProcessesPerThread = 5;
      int totalNumberOfTasks = 2 * numberOfThreads * numberOfProcessesPerThread;
      
      ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(numberOfThreads));
      
      for(int i=0; i< numberOfThreads; i++) {
        executor.execute(new ConcurrentProcessRunnerRunnable(numberOfProcessesPerThread, "kermit" + i));
      }
      
      // Wait for termination or timeout and check if all tasks are complete
      executor.shutdown();
      boolean isEnded = executor.awaitTermination(20000, TimeUnit.MILLISECONDS);
      if(!isEnded) {
        log.error("Executor was not shut down after timeout, not al tasks have been executed");
        executor.shutdownNow();
        
      }
      assertEquals(0, executor.getActiveCount());
      
      // Check there are no processes active anymore
      assertEquals(0, runtimeService.createProcessInstanceQuery().count());
      
      if(processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
        // Check if all processes and tasks are complete
        assertEquals(numberOfProcessesPerThread * numberOfThreads, historyService.createHistoricProcessInstanceQuery()
                .finished().count());
        assertEquals(totalNumberOfTasks, historyService.createHistoricTaskInstanceQuery()
                .finished().count());
      }
    }
  }
  
  protected void retryStartProcess(String runningUser) {
    int retries = MAX_RETRIES;
    int timeout = 200;
    boolean success = false;
    while(retries > 0 && !success) {
      try {
        runtimeService.startProcessInstanceByKey("concurrentProcess", Collections.singletonMap("assignee", (Object)runningUser));
        success = true;
      } catch(PersistenceException pe) {
        retries = retries - 1;
        log.debug("Retrying process start - " + (MAX_RETRIES - retries));
        try {
          Thread.sleep(timeout);
{'fraction_non_alphanumeric': 0.08816225165562915, 'fraction_numerical': 0.008830022075055188, 'mean_word_length': 3.7628120893561103, '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': '2775869', 'n_tokens_mistral': 1991, 'n_tokens_neox': 1929, 'n_words': 528}