<commit_before>/*
 * Copyright (c) 2011 LinkedIn, Inc
 * 
 * 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 cleo.search.typeahead;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import cleo.search.Element;
import cleo.search.IndexRoller;
import cleo.search.collector.Collector;
import cleo.search.filter.BloomFilter;
import cleo.search.selector.Selector;
import cleo.search.selector.SelectorContext;
import cleo.search.selector.SelectorFactory;
import cleo.search.store.ArrayStoreElement;
import cleo.search.util.DaemonThreadFactory;

/**
 * RollingTypeahead
 * 
 * @author jwu
 * @since 03/02, 2011
 */
class RollingTypeahead<E extends Element> extends AbstractTypeahead<E> {
  public static final int DEFAULT_ROLLING_SIZE = 100;
  
  private final static Logger logger = Logger.getLogger(RollingTypeahead.class);
  private final ExecutorService executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
  private final Queue<FilterEntry<E>> elementQueue = new ConcurrentLinkedQueue<FilterEntry<E>>();
  private final Map<Integer, E> elementMap = Collections.synchronizedMap(new HashMap<Integer, E>());
  private final RollingDriver rollingDriver;
  private volatile IndexRoller<E> indexRoller;
  private volatile int rollingSize = DEFAULT_ROLLING_SIZE;
  
  public RollingTypeahead(String name,
                          IndexRoller<E> indexRoller,
                          ArrayStoreElement<E> elementStore,
                          SelectorFactory<E> selectorFactory,
                          BloomFilter<Long> bloomFilter) {
    this(name,
         DEFAULT_ROLLING_SIZE,
         indexRoller,
         elementStore,
         selectorFactory,
         bloomFilter);
  }
  
  public RollingTypeahead(String name,
                          int rollingSize,
                          IndexRoller<E> indexRoller,
                          ArrayStoreElement<E> elementStore,
                          SelectorFactory<E> selectorFactory,
                          BloomFilter<Long> bloomFilter) {
    super(name, elementStore, selectorFactory, bloomFilter);
    
    this.indexRoller = indexRoller;
    this.setRollingSize(rollingSize);
    this.rollingDriver = new RollingDriver();
    this.executor.execute(rollingDriver);
  }
  
  class RollingDriver implements Runnable {
    private final long rollingTime = 1000L;
    private final long maxSleepTime = 500L;
    private final long minSleepTime =  10L;
    private volatile boolean active = true;
    private final Object mutex = new Object();
    
    @Override
    public void run() {
      while(active) {
        synchronized(mutex) {
          if(elementQueue.size() >= rollingSize) {
            int cnt = 0;
            List<E> list = new ArrayList<E>(rollingSize);
            Iterator<FilterEntry<E>> iter = elementQueue.iterator();
            while(iter.hasNext()) {
              list.add(iter.next().element);
              if(++cnt == rollingSize) break;
            }
            
            roll(list, false);
          }
        }
        
        // RollingUpdater sleep
        long sleepTime = (rollingSize - elementQueue.size()) * rollingTime / rollingSize;
        sleepTime = Math.max(minSleepTime, sleepTime);
        sleepTime = Math.min(maxSleepTime, sleepTime);
        if(sleepTime > minSleepTime) {
          try {
            Thread.sleep(maxSleepTime);
          } catch (InterruptedException e) {}
        }
      }
      
      drain();
    }
    
    private void roll(List<E> list, boolean clearAll) {
      try {
        if(indexRoller == null) {
          logger.warn("rolling update failure: no rolling handler");
        } else {
          if(indexRoller.roll(list)) {
            logger.info("rolling update success: removed " + list.size()  + " updates");<commit_msg>roll updates in one second<commit_after>/*
 * Copyright (c) 2011 LinkedIn, Inc
 * 
 * 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 cleo.search.typeahead;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import cleo.search.Element;
import cleo.search.IndexRoller;
import cleo.search.collector.Collector;
import cleo.search.filter.BloomFilter;
import cleo.search.selector.Selector;
import cleo.search.selector.SelectorContext;
import cleo.search.selector.SelectorFactory;
import cleo.search.store.ArrayStoreElement;
import cleo.search.util.DaemonThreadFactory;

/**
 * RollingTypeahead
 * 
 * @author jwu
 * @since 03/02, 2011
 * 
 * <p>
 * 01/09, 2012 - Roll updates in one second <br/>
 */
class RollingTypeahead<E extends Element> extends AbstractTypeahead<E> {
  public static final int DEFAULT_ROLLING_SIZE = 100;
  
  private final static Logger logger = Logger.getLogger(RollingTypeahead.class);
  private final ExecutorService executor = Executors.newSingleThreadExecutor(new DaemonThreadFactory());
  private final Queue<FilterEntry<E>> elementQueue = new ConcurrentLinkedQueue<FilterEntry<E>>();
  private final Map<Integer, E> elementMap = Collections.synchronizedMap(new HashMap<Integer, E>());
  private final RollingDriver rollingDriver;
  private volatile IndexRoller<E> indexRoller;
  private volatile int rollingSize = DEFAULT_ROLLING_SIZE;
  
  public RollingTypeahead(String name,
                          IndexRoller<E> indexRoller,
                          ArrayStoreElement<E> elementStore,
                          SelectorFactory<E> selectorFactory,
                          BloomFilter<Long> bloomFilter) {
    this(name,
         DEFAULT_ROLLING_SIZE,
         indexRoller,
         elementStore,
         selectorFactory,
         bloomFilter);
  }
  
  public RollingTypeahead(String name,
                          int rollingSize,
                          IndexRoller<E> indexRoller,
                          ArrayStoreElement<E> elementStore,
                          SelectorFactory<E> selectorFactory,
                          BloomFilter<Long> bloomFilter) {
    super(name, elementStore, selectorFactory, bloomFilter);
    
    this.indexRoller = indexRoller;
    this.setRollingSize(rollingSize);
    this.rollingDriver = new RollingDriver();
    this.executor.execute(rollingDriver);
  }
  
  class RollingDriver implements Runnable {
    private final long rollingTime = 1000L; // 1000 Milliseconds
    private final long minSleepTime = 100L; //  100 Milliseconds
    private volatile boolean active = true;
    private final Object mutex = new Object();
    
    @Override
    public void run() {
      int rolled = 0;
      while(active) {
        rolled = 0;
        
        synchronized(mutex) {
          if(elementQueue.size() > 0) {
            // Collect elements up to the specified rollingSize
            Iterator<FilterEntry<E>> iter = elementQueue.iterator();
            List<E> list = new ArrayList<E>(rollingSize);
            while(iter.hasNext()) {
              list.add(iter.next().element);
              if(list.size() >= rollingSize) break;
            }
            
            roll(list, false);
            rolled = list.size();
          }
        }
        
        // Sleep if no elements in the queue
        if(elementQueue.size() == 0) {
          try {
            long sleepTime = (rollingSize - rolled) * rollingTime / rollingSize;
            sleepTime = Math.max(minSleepTime, sleepTime);
            Thread.sleep(sleepTime);
          } catch (InterruptedException e) {}
        }
      }
      
      drain();
    }
    
    private void roll(List<E> list, boolean clearAll) {
      try {
        if(indexRoller == null) {
          logger.warn("rolling update failure: no rolling handler");
        } else {
          if(indexRoller.roll(list)) {
            logger.info("rolling update success: removed " + list.size()  + " updates");
{'fraction_non_alphanumeric': 0.09005246814434094, 'fraction_numerical': 0.008137916265124745, 'mean_word_length': 2.6598746081504703, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 53, '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': '7318114', 'n_tokens_mistral': 2593, 'n_tokens_neox': 2481, 'n_words': 672}