Optional operations to do before the multiple-threads start indexing

@param backend
496186
private void beforeBatch(BatchBackend backend) {
		if ( this.purgeAtStart ) {
			// purgeAll for affected entities
			IndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );
			for ( IndexedTypeIdentifier type : targetedTypes ) {
				// needs do be in-sync work to make sure we wait for the end of it.
				backend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );
			}
			if ( this.optimizeAfterPurge ) {
				backend.optimize( targetedTypes );
			}
		}
	}
1179478
public void prepare(Collection<String> surts) {
        List<String> safeSurts = new ArrayList<String>(surts);
        FetchThread threads[] = new FetchThread[PREPARE_THREAD_COUNT ];
        for (int i = 0; i < PREPARE_THREAD_COUNT ; i++) {
            threads[i] = new FetchThread(safeSurts);
            threads[i].start();
        }
        for (int i = 0; i < PREPARE_THREAD_COUNT ; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
            }
        }
    }
501854
void insertBackwardEdge(final ManagementEdge managementEdge, final int index) {

		while (index >= this.backwardEdges.size()) {
			this.backwardEdges.add(null);
		}

		this.backwardEdges.set(index, managementEdge);
	}
851100
private void initializeIfNeeded() throws BackendInitializationException,
            BackendNewInstanceException {
        if (isClosed()) {
            throw new IllegalStateException("Knowledge source already closed!");
        }
        if (this.inDataSourceGetter == null) {
            this.inDataSourceGetter
                    = new SubtreePropositionDefinitionGetterRegular(this, true);
        }
        if (this.collectSubtreeGetter == null) {
            this.collectSubtreeGetter
                    = new SubtreePropositionDefinitionGetterRegular(this, false);
        }
    }
1340051
protected void onBeforeRender() {
        super.onBeforeRender();
        if (runtimeModel.isEdit()) {
            for (QueryParameter parameter : convertMap.values()) {
                populateDependentParameters(parameter, null);
            }
        }
    }
1203755
@Subscribe
    public void handleIndexSetCreation(final IndexSetCreatedEvent event) {
        final String indexSetId = event.indexSet().id();
        // We are NOT using IndexSetRegistry#get(String) here because of this: https://github.com/Graylog2/graylog2-server/issues/4625
        final Optional<IndexSetConfig> optionalIndexSet = indexSetService.get(indexSetId);

        if (optionalIndexSet.isPresent()) {
            schedule(mongoIndexSetFactory.create(optionalIndexSet.get()));
        } else {
            LOG.warn("Couldn't find newly created index set <{}>", indexSetId);
        }
    }
1007467
void runInternal() throws IOException, BackoffException {
        LOG.info("Starting to listen for events for {}", eventNames);

        JsonInput jsonInput = openJsonInput();

        int errorCount = 0;

        while (true) {
            try {
                final JsonParser jsonParser = jsonInput.getJsonParser();

                if (Thread.currentThread().isInterrupted()) {
                    throw new InterruptedIOException("Interrupted");
                }

                readBatch(jsonParser);

                errorCount = 0;
            } catch (IOException e) {
                // Remember interrupted flag in case it accidentally gets cleared before the break
                final boolean wasInterrupted = Thread.currentThread().isInterrupted();

                metricsCollector.markErrorWhileConsuming();

                if (errorCount > 0) {
                    LOG.warn("Got [{}] [{}] while reading events for {} after [{}] retries", e.getClass().getSimpleName(), e.getMessage(), eventNames, errorCount, e);
                } else {
                    LOG.info("Got [{}] [{}] while reading events for {}", e.getClass().getSimpleName(), e.getMessage(), eventNames, e);
                }

                jsonInput.close();

                if (wasInterrupted || Thread.currentThread().isInterrupted()) {
                    LOG.warn("Thread was interrupted");
                    break;
                }

                try {
                    LOG.debug("Reconnecting after [{}] errors", errorCount);
                    jsonInput = backoffStrategy.call(errorCount, e, this::openJsonInput);
                    LOG.info("Reconnected after [{}] errors", errorCount);
                    metricsCollector.markReconnection();
                } catch (InterruptedException interruptedException) {
                    LOG.warn("Interrupted during reconnection", interruptedException);

                    Thread.currentThread().interrupt();
                    return;
                }

                errorCount++;
            } catch (Throwable e) {
                LOG.warn("Got [{}] [{}] while reading events for {}", e.getClass().getSimpleName(), e.getMessage(), eventNames, e);

                try {
                    jsonInput.close();
                } catch (Throwable suppressed) {
                    e.addSuppressed(e);
                }
                throw e;
            }
        }
    }
31827
private synchronized static void startBackgroundThread() {
        if (backgroundThread == null) {
            backgroundThreadMayRun = true;
            backgroundThread = new Thread(asyncThreadGroup, "AnalyticsBackgroundThread") {
                public void run() {
                    logger.debug("AnalyticsBackgroundThread started");
                    while (backgroundThreadMayRun) {
                        try {
                            String url = null;
                            
                            synchronized (fifo) {
                                if (fifo.isEmpty()) {
                                    fifo.wait();
                                }
                                
                                if (!fifo.isEmpty()) {
                                    // Get a reference to the oldest element in the FIFO, but leave it in the FIFO until it is processed.
                                    url = fifo.getFirst();
                                }
                            }
                            
                            if (url != null) {
                                try {
                                    dispatchRequest(url);
                                } finally {
                                    // Now that we have completed the HTTP request to GA, remove the element from the FIFO.
                                    synchronized (fifo) {
                                        fifo.removeFirst();
                                    }
                                }
                            }
                        } catch (Exception e) {
                        	logger.error("Got exception from dispatch thread",e);
                        }
                    }
                }
            };
            
            // Don't prevent the application from terminating.
            // Use completeBackgroundTasks() before exit if you want to ensure that all pending GA requests are sent. 
            backgroundThread.setDaemon(true);
            
            backgroundThread.start();
        }        
    }
1310809
public void flushSomeAvailableRowsFrom(final XMLUtil util, final Appendable appendable, final int rowIndex)
            throws IOException {
        if (rowIndex == 0)
            this.appendPreamble(util, appendable);
        this.appendRows(util, appendable, rowIndex);
    }
558266
public void cacheThreadLocalRawStore() {
    Long threadId = this.getId();
    RawStore threadLocalRawStore = HiveMetaStore.HMSHandler.getRawStore();
    if (threadLocalRawStore != null && !threadRawStoreMap.containsKey(threadId)) {
      LOG.debug("Adding RawStore: " + threadLocalRawStore + ", for the thread: " +
          this.getName() + " to threadRawStoreMap for future cleanup.");
      threadRawStoreMap.put(threadId, threadLocalRawStore);
    }
  }
362135
public function initializeIndexQueueAction()
    {
        $initializedIndexingConfigurations = [];

        $indexingConfigurationsToInitialize = GeneralUtility::_POST('tx_solr-index-queue-initialization');
        if ((!empty($indexingConfigurationsToInitialize)) && (is_array($indexingConfigurationsToInitialize))) {
            // initialize selected indexing configuration
            $initializedIndexingConfigurations = $this->indexQueue->getInitializationService()->initializeBySiteAndIndexConfigurations($this->selectedSite, $indexingConfigurationsToInitialize);
        } else {
            $messageLabel = 'solr.backend.index_queue_module.flashmessage.initialize.no_selection';
            $titleLabel = 'solr.backend.index_queue_module.flashmessage.not_initialized.title';
            $this->addFlashMessage(
                LocalizationUtility::translate($messageLabel, 'Solr'),
                LocalizationUtility::translate($titleLabel, 'Solr'),
                FlashMessage::WARNING
            );
        }
        $messagesForConfigurations = [];
        foreach (array_keys($initializedIndexingConfigurations) as $indexingConfigurationName) {
            $itemCount = $this->indexQueue->getStatisticsBySite($this->selectedSite, $indexingConfigurationName)->getTotalCount();
            $messagesForConfigurations[] = $indexingConfigurationName . ' (' . $itemCount . ' records)';
        }

        if (!empty($initializedIndexingConfigurations)) {
            $messageLabel = 'solr.backend.index_queue_module.flashmessage.initialize.success';
            $titleLabel = 'solr.backend.index_queue_module.flashmessage.initialize.title';
            $this->addFlashMessage(
                LocalizationUtility::translate($messageLabel, 'Solr', [implode(', ', $messagesForConfigurations)]),
                LocalizationUtility::translate($titleLabel, 'Solr'),
                FlashMessage::OK
            );
        }

        $this->redirect('index');
    }
1143284
private void processInitialization() {
        ExecutorService executorService = Executors.newFixedThreadPool(this.maxThread);
        this.postInitializingMethods.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(entry -> {
            log.debug("Found {} beans with max threads {} and order {}", entry.getValue().size(), this.maxThread, entry.getKey());
            try {
                executorService.invokeAll(entry.getValue());
            } catch (InterruptedException e) {
                log.warn("Failed to invoke {} method(s) on executorService {}", entry.getValue().size(), executorService);
            }
        });
        executorService.shutdown();
    }
1019522
@Override
    protected void doActionsInSwingThread() {
        if (component instanceof JComboBox) {
            ((JComboBox) component).setSelectedIndex(mIndex);
        } else if (component instanceof JList) {
            ((JList) component).setSelectedIndex(mIndex);
        }
    }
173628
protected void beforeLoading()
    {
        if (_listeners != null)
        {
            CollectionProxyListener listener;

            if (_perThreadDescriptorsEnabled) {
                loadProfileIfNeeded();
            }
            for (int idx = _listeners.size() - 1; idx >= 0; idx--)
            {
                listener = (CollectionProxyListener)_listeners.get(idx);
                listener.beforeLoading(this);
            }
        }
    }
918950
@Override
	public void setCustomPostprocessors(Map<String, String> keysClassNames) {
		for (Entry<String, String> entry : keysClassNames.entrySet()) {
			ResourceBundlePostProcessor customProcessor = (ResourceBundlePostProcessor) ClassLoaderResourceUtils
					.buildObjectInstance((String) entry.getValue());
			boolean isVariantPostProcessor = customProcessor.getClass()
					.getAnnotation(VariantPostProcessor.class) != null;

			if (customProcessor instanceof BundlingProcessLifeCycleListener) {
				listeners.add((BundlingProcessLifeCycleListener) customProcessor);
			}
			String key = (String) entry.getKey();
			customPostProcessors.put(key, getCustomProcessorWrapper(customProcessor, key, isVariantPostProcessor));
		}
	}
799488
private void doInBackup(List<DelayedEntry> delayedEntries) {
        writeBehindProcessor.callBeforeStoreListeners(delayedEntries);
        removeFinishedStoreOperationsFromQueues(mapName, delayedEntries);
        writeBehindProcessor.callAfterStoreListeners(delayedEntries);
    }
774788
public BackendTransaction beginTransaction(TransactionConfiguration configuration, KeyInformation.Retriever indexKeyRetriever) throws BackendException {

        StoreTransaction tx = storeManagerLocking.beginTransaction(configuration);

        // Cache
        CacheTransaction cacheTx = new CacheTransaction(tx, storeManagerLocking, bufferSize, maxWriteTime, configuration.hasEnabledBatchLoading());

        // Index transactions
        Map<String, IndexTransaction> indexTx = new HashMap<String, IndexTransaction>(indexes.size());
        for (Map.Entry<String, IndexProvider> entry : indexes.entrySet()) {
            indexTx.put(entry.getKey(), new IndexTransaction(entry.getValue(), indexKeyRetriever.get(entry.getKey()), configuration, maxWriteTime));
        }

        return new BackendTransaction(cacheTx, configuration, storeFeatures,
                edgeStore, indexStore, txLogStore,
                maxReadTime, indexTx, threadPool);
    }