Apache Lucene open-source search software
Merge latest trunk into realtime branch
Michael Buschd2e8071472cc
diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.javaindex d0edac225c0,7461ce52fa9..2e45f6a21df--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java@@@ -19,13 -19,13 +19,11 @@@ package org.apache.lucene.indeximport java.io.IOException;import java.io.PrintStream;-import java.text.NumberFormat;-import java.util.ArrayList;import java.util.Collection;-import java.util.HashMap;-import java.util.HashSet;+import java.util.Iterator;import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;- import java.util.concurrent.locks.Lock;- import java.util.concurrent.locks.ReentrantLock;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.document.Document;@@@ -115,16 -130,13 +113,15 @@@ final class DocumentsWriterint maxFieldLength = IndexWriterConfig.UNLIMITED_FIELD_LENGTH;Similarity similarity;- // max # simultaneous threads; if there are more than- // this, they wait for others to finish first- private final int maxThreadStates;+ List<String> newFiles;++ private final DocumentsWriterThreadPool threadPool;+ final IndexWriter indexWriter;- private final Lock sequenceIDLock = new ReentrantLock();++ private AtomicInteger numDocsInRAM = new AtomicInteger(0);+ private AtomicLong ramUsed = new AtomicLong(0);+ private int numDocumentsWriterPerThreads;- // Deletes for our still-in-RAM (to be flushed next) segment- private SegmentDeletes pendingDeletes = new SegmentDeletes();-static class DocState {DocumentsWriter docWriter;Analyzer analyzer;@@@ -344,130 -655,375 +341,122 @@@notifyAll();}- DocumentsWriterPerThread newDocumentsWriterPerThread() {- /** Returns a free (idle) ThreadState that may be used for- * indexing this one document. This call also pauses if a- * flush is pending. If delTerm is non-null then we- * buffer this deleted term after the thread state has- * been acquired. */- synchronized DocumentsWriterThreadState getThreadState(Document doc, Term delTerm) throws IOException {-- final Thread currentThread = Thread.currentThread();- assert !Thread.holdsLock(writer);-- // First, find a thread state. If this thread already- // has affinity to a specific ThreadState, use that one- // again.- DocumentsWriterThreadState state = threadBindings.get(currentThread);- if (state == null) {-- // First time this thread has called us since last- // flush. Find the least loaded thread state:- DocumentsWriterThreadState minThreadState = null;- for(int i=0;i<threadStates.length;i++) {- DocumentsWriterThreadState ts = threadStates[i];- if (minThreadState == null || ts.numThreads < minThreadState.numThreads) {- minThreadState = ts;- }- }- if (minThreadState != null && (minThreadState.numThreads == 0 || threadStates.length >= maxThreadStates)) {- state = minThreadState;- state.numThreads++;- } else {- // Just create a new "private" thread state- DocumentsWriterThreadState[] newArray = new DocumentsWriterThreadState[1+threadStates.length];- if (threadStates.length > 0) {- System.arraycopy(threadStates, 0, newArray, 0, threadStates.length);- }- state = newArray[threadStates.length] = new DocumentsWriterThreadState(this);- threadStates = newArray;- }- threadBindings.put(currentThread, state);- }-- // Next, wait until my thread state is idle (in case- // it's shared with other threads), and no flush/abort- // pending- waitReady(state);-- // Allocate segment name if this is the first doc since- // last flush:- if (segment == null) {- segment = writer.newSegmentName();- assert numDocs == 0;- }-- state.docState.docID = nextDocID++;-- if (delTerm != null) {- pendingDeletes.addTerm(delTerm, state.docState.docID);- }-- numDocs++;- state.isIdle = false;- return state;- }-- boolean addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException {- return updateDocument(doc, analyzer, null);++ synchronized DocumentsWriterPerThread newDocumentsWriterPerThread() {+ DocumentsWriterPerThread perThread = new DocumentsWriterPerThread(directory, this, chain);- sequenceIDLock.lock();- try {- numDocumentsWriterPerThreads++;- return perThread;- } finally {- sequenceIDLock.unlock();- }++ numDocumentsWriterPerThreads++;++ return perThread;}-- boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm)- throws CorruptIndexException, IOException {-- // Possibly trigger a flush, or wait until any running flush completes:- boolean doFlush = flushControl.waitUpdate(1, delTerm != null ? 1 : 0);- // This call is synchronized but fast- final DocumentsWriterThreadState state = getThreadState(doc, delTerm);+ boolean updateDocument(final Document doc, final Analyzer analyzer, final Term delTerm)+ throws CorruptIndexException, IOException {- final DocState docState = state.docState;- docState.doc = doc;- docState.analyzer = analyzer;-- boolean success = false;- try {- // This call is not synchronized and does all the- // work- final DocWriter perDoc;- try {- perDoc = state.consumer.processDocument();- } finally {- docState.clear();- }-- // This call is synchronized but fast- finishDocument(state, perDoc);-- success = true;- } finally {- if (!success) {-- // If this thread state had decided to flush, we- // must clear it so another thread can flush- if (doFlush) {- flushControl.clearFlushPending();- }-- if (infoStream != null) {- message("exception in updateDocument aborting=" + aborting);- }+ boolean flushed = threadPool.executePerThread(this, doc,+ new DocumentsWriterThreadPool.PerThreadTask<Boolean>() {+ @Override+ public Boolean process(final DocumentsWriterPerThread perThread) throws IOException {+ long perThreadRAMUsedBeforeAdd = perThread.bytesUsed();+ perThread.addDocument(doc, analyzer);- sequenceIDLock.lock();- synchronized(this) {-- state.isIdle = true;- notifyAll();-- if (aborting) {- abort();- } else {- skipDocWriter.docID = docState.docID;- boolean success2 = false;-- try {- waitQueue.add(skipDocWriter);- success2 = true;- } finally {- if (!success2) {- abort();- return false;++ synchronized(DocumentsWriter.this) {+ ensureOpen();+ if (delTerm != null) {+ deleteTerm(delTerm, true);}+ perThread.commitDocument();+ numDocsInRAM.incrementAndGet();- } finally {- sequenceIDLock.unlock();}- // Immediately mark this document as deleted- // since likely it was partially added. This- // keeps indexing as "all or none" (atomic) when- // adding a document:- deleteDocID(state.docState.docID);+ if (finishAddDocument(perThread, perThreadRAMUsedBeforeAdd)) {+ super.clearThreadBindings();+ return true;+ }+ return false;}- }- }- }+ });- doFlush |= flushControl.flushByRAMUsage("new document");+ if (flushed) {+ indexWriter.maybeMerge();+ return true;+ }- return doFlush;+ return false;}- public synchronized void waitIdle() {- while (!allThreadsIdle()) {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);+ private final boolean finishAddDocument(DocumentsWriterPerThread perThread,+ long perThreadRAMUsedBeforeAdd) throws IOException {+ int numDocsPerThread = perThread.getNumDocsInRAM();+ boolean flushed = maybeFlushPerThread(perThread);+ if (flushed) {+ int oldValue = numDocsInRAM.get();+ while (!numDocsInRAM.compareAndSet(oldValue, oldValue - numDocsPerThread)) {+ oldValue = numDocsInRAM.get();}}- }- synchronized void waitReady(DocumentsWriterThreadState state) {- while (!closed && (!state.isIdle || aborting)) {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);- }+ long deltaRAM = perThread.bytesUsed() - perThreadRAMUsedBeforeAdd;+ long oldValue = ramUsed.get();+ while (!ramUsed.compareAndSet(oldValue, oldValue + deltaRAM)) {+ oldValue = ramUsed.get();}- if (closed) {- throw new AlreadyClosedException("this IndexWriter is closed");- }+ return flushed;}- /** Does the synchronized work to finish/flush the- * inverted document. */- private void finishDocument(DocumentsWriterThreadState perThread, DocWriter docWriter) throws IOException {-- // Must call this w/o holding synchronized(this) else- // we'll hit deadlock:- balanceRAM();-- synchronized(this) {-- assert docWriter == null || docWriter.docID == perThread.docState.docID;-- if (aborting) {-- // We are currently aborting, and another thread is- // waiting for me to become idle. We just forcefully- // idle this threadState; it will be fully reset by- // abort()- if (docWriter != null) {- try {- docWriter.abort();- } catch (Throwable t) {- }- }-- perThread.isIdle = true;-- // wakes up any threads waiting on the wait queue- notifyAll();-- return;- }-- final boolean doPause;-- if (docWriter != null) {- doPause = waitQueue.add(docWriter);- } else {- skipDocWriter.docID = perThread.docState.docID;- doPause = waitQueue.add(skipDocWriter);- }-- if (doPause) {- waitForWaitQueue();- }-- perThread.isIdle = true;-- // wakes up any threads waiting on the wait queue- notifyAll();+ private boolean flushSegment(DocumentsWriterPerThread perThread) throws IOException {+ if (perThread.getNumDocsInRAM() == 0) {+ return false;}- }- synchronized void waitForWaitQueue() {- do {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);- }- } while (!waitQueue.doResume());- }+ SegmentInfo newSegment = perThread.flush();+ newSegment.dir = indexWriter.getDirectory();- private static class SkipDocWriter extends DocWriter {- @Override- void finish() {- }- @Override- void abort() {- }- @Override- long sizeInBytes() {- return 0;- }+ finishFlushedSegment(newSegment, perThread);+ return true;}- final SkipDocWriter skipDocWriter = new SkipDocWriter();-- NumberFormat nf = NumberFormat.getInstance();-- /* Initial chunks size of the shared byte[] blocks used to- store postings data */- final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;-- /* if you increase this, you must fix field cache impl for- * getTerms/getTermsIndex requires <= 32768 */- final static int MAX_TERM_LENGTH_UTF8 = BYTE_BLOCK_SIZE-2;- /* Initial chunks size of the shared int[] blocks used to- store postings data */- final static int INT_BLOCK_SHIFT = 13;- final static int INT_BLOCK_SIZE = 1 << INT_BLOCK_SHIFT;- final static int INT_BLOCK_MASK = INT_BLOCK_SIZE - 1;+ private final boolean maybeFlushPerThread(DocumentsWriterPerThread perThread) throws IOException {+ if (perThread.getNumDocsInRAM() == maxBufferedDocs) {+ flushSegment(perThread);+ assert perThread.getNumDocsInRAM() == 0;- private List<int[]> freeIntBlocks = new ArrayList<int[]>();-- /* Allocate another int[] from the shared pool */- synchronized int[] getIntBlock() {- final int size = freeIntBlocks.size();- final int[] b;- if (0 == size) {- b = new int[INT_BLOCK_SIZE];- bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);- } else {- b = freeIntBlocks.remove(size-1);+ return true;}- return b;- }- long bytesUsed() {- return bytesUsed.get() + pendingDeletes.bytesUsed.get();+ return false;}- /* Return int[]s to the pool */- synchronized void recycleIntBlocks(int[][] blocks, int start, int end) {- for(int i=start;i<end;i++) {- freeIntBlocks.add(blocks[i]);- blocks[i] = null;- }- }+ final boolean flushAllThreads(final boolean flushDeletes)+ throws IOException {- final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);+ return threadPool.executeAllThreads(this, new DocumentsWriterThreadPool.AllThreadsTask<Boolean>() {+ @Override+ public Boolean process(Iterator<DocumentsWriterPerThread> threadsIterator) throws IOException {+ boolean anythingFlushed = false;- final static int PER_DOC_BLOCK_SIZE = 1024;+ while (threadsIterator.hasNext()) {+ DocumentsWriterPerThread perThread = threadsIterator.next();+ final int numDocs = perThread.getNumDocsInRAM();- final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);+ // Always flush docs if there are any+ boolean flushDocs = numDocs > 0;- String toMB(long v) {- return nf.format(v/1024./1024.);- }+ String segment = perThread.getSegment();- /* We have three pools of RAM: Postings, byte blocks- * (holds freq/prox posting data) and per-doc buffers- * (stored fields/term vectors). Different docs require- * varying amount of storage from these classes. For- * example, docs with many unique single-occurrence short- * terms will use up the Postings RAM and hardly any of- * the other two. Whereas docs with very large terms will- * use alot of byte blocks RAM. This method just frees- * allocations from the pools once we are over-budget,- * which balances the pools to match the current docs. */- void balanceRAM() {-- final boolean doBalance;- final long deletesRAMUsed;-- deletesRAMUsed = bufferedDeletes.bytesUsed();-- synchronized(this) {- if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) {- return;- }-- doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize;- }+ // If we are flushing docs, segment must not be null:+ assert segment != null || !flushDocs;- if (doBalance) {+ if (flushDocs) {+ SegmentInfo newSegment = perThread.flush();+ newSegment.dir = indexWriter.getDirectory();- if (infoStream != null) {- message(" RAM: balance allocations: usedMB=" + toMB(bytesUsed()) +- " vs trigger=" + toMB(ramBufferSize) +- " deletesMB=" + toMB(deletesRAMUsed) +- " byteBlockFree=" + toMB(byteBlockAllocator.bytesUsed()) +- " perDocFree=" + toMB(perDocAllocator.bytesUsed()));- }+ if (newSegment != null) {+ anythingFlushed = true;- final long startBytesUsed = bytesUsed() + deletesRAMUsed;-- int iter = 0;-- // We free equally from each pool in 32 KB- // chunks until we are below our threshold- // (freeLevel)-- boolean any = true;-- while(bytesUsed()+deletesRAMUsed > freeLevel) {-- synchronized(this) {- if (0 == perDocAllocator.numBufferedBlocks() &&- 0 == byteBlockAllocator.numBufferedBlocks() &&- 0 == freeIntBlocks.size() && !any) {- // Nothing else to free -- must flush now.- bufferIsFull = bytesUsed()+deletesRAMUsed > ramBufferSize;- if (infoStream != null) {- if (bytesUsed()+deletesRAMUsed > ramBufferSize) {- message(" nothing to free; set bufferIsFull");- } else {- message(" nothing to free");- }+ IndexWriter.setDiagnostics(newSegment, "flush");+ finishFlushedSegment(newSegment, perThread);}- break;- }-- if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) {- byteBlockAllocator.freeBlocks(1);- }- if ((1 == iter % 4) && freeIntBlocks.size() > 0) {- freeIntBlocks.remove(freeIntBlocks.size()-1);- bytesUsed.addAndGet(-INT_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT);- }- if ((2 == iter % 4) && perDocAllocator.numBufferedBlocks() > 0) {- perDocAllocator.freeBlocks(32); // Remove upwards of 32 blocks (each block is 1K)+ } else if (flushDeletes) {+ perThread.pushDeletes(null, indexWriter.segmentInfos);}}