Apache Lucene open-source search software
Merged with Trunk
Simon Willnauer98dffb255d5b
diff --cc dev-tools/idea/lucene/lucene.imlindex c6dd9276e7e,e16ece78925..bddb309e6c8--- a/dev-tools/idea/lucene/lucene.iml+++ b/dev-tools/idea/lucene/lucene.iml@@@ -6,8 -6,10 +6,9 @@@<exclude-output /><content url="file://$MODULE_DIR$"><sourceFolder url="file://$MODULE_DIR$/src/java" isTestSource="false" />- <sourceFolder url="file://$MODULE_DIR$/src/test-framework" isTestSource="true" /><sourceFolder url="file://$MODULE_DIR$/src/test" isTestSource="true" /><excludeFolder url="file://$MODULE_DIR$/build" />+ <excludeFolder url="file://$MODULE_DIR$/dist" /></content><orderEntry type="inheritedJdk" /><orderEntry type="sourceFolder" forTests="false" />diff --cc dev-tools/maven/lucene/contrib/ant/pom.xml.templateindex cc03f19354e,e300d0f8ada..7071e96dcef--- a/dev-tools/maven/lucene/contrib/ant/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/ant/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/db/bdb-je/pom.xml.templateindex fd5934f0146,a5d7647b526..32841229342--- a/dev-tools/maven/lucene/contrib/db/bdb-je/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/db/bdb-je/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/db/bdb/pom.xml.templateindex cf17c674cfe,d5d5123ab5f..2a249e5884d--- a/dev-tools/maven/lucene/contrib/db/bdb/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/db/bdb/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/demo/pom.xml.templateindex 1411cb43ab8,7672424141e..e51ba82e31c--- a/dev-tools/maven/lucene/contrib/demo/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/demo/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/highlighter/pom.xml.templateindex 8cf32e3e524,b54c05fe627..d435d4b6481--- a/dev-tools/maven/lucene/contrib/highlighter/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/highlighter/pom.xml.template@@@ -45,9 -45,8 +45,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/instantiated/pom.xml.templateindex c2a9e2ccc0f,bc8b0e3167b..d06359efc36--- a/dev-tools/maven/lucene/contrib/instantiated/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/instantiated/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/lucli/pom.xml.templateindex f7928415bd6,efa4c53a882..7e5615c0fa6--- a/dev-tools/maven/lucene/contrib/lucli/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/lucli/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/memory/pom.xml.templateindex 5922bf57fd3,8017f82f325..8bef7fa4c6f--- a/dev-tools/maven/lucene/contrib/memory/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/memory/pom.xml.template@@@ -45,9 -45,8 +45,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/spatial/pom.xml.templateindex da42c87f02f,1b822d7c935..e2063098d0a--- a/dev-tools/maven/lucene/contrib/spatial/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/spatial/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/spellchecker/pom.xml.templateindex a65a1078c58,93e0a58ef73..e21b6a8dde5--- a/dev-tools/maven/lucene/contrib/spellchecker/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/spellchecker/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/swing/pom.xml.templateindex 31af98689e1,bb5178d1b60..6d4fdf35cf1--- a/dev-tools/maven/lucene/contrib/swing/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/swing/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/wordnet/pom.xml.templateindex 6a4604f86fd,458a6e0c214..2f18e376fe8--- a/dev-tools/maven/lucene/contrib/wordnet/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/wordnet/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/lucene/contrib/xml-query-parser/pom.xml.templateindex 66efaab58bd,b22d23719f6..f5fbd622830--- a/dev-tools/maven/lucene/contrib/xml-query-parser/pom.xml.template+++ b/dev-tools/maven/lucene/contrib/xml-query-parser/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/modules/analysis/phonetic/pom.xml.templateindex 78098cb1d59,b641f8a33dc..2cdc3dd5ded--- a/dev-tools/maven/modules/analysis/phonetic/pom.xml.template+++ b/dev-tools/maven/modules/analysis/phonetic/pom.xml.template@@@ -45,9 -45,8 +45,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/modules/analysis/smartcn/pom.xml.templateindex 10f1e915651,8a1239a7c64..fcf5550b0c7--- a/dev-tools/maven/modules/analysis/smartcn/pom.xml.template+++ b/dev-tools/maven/modules/analysis/smartcn/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/modules/analysis/stempel/pom.xml.templateindex 979498fd370,4e1cc7da812..4f10e0d1c84--- a/dev-tools/maven/modules/analysis/stempel/pom.xml.template+++ b/dev-tools/maven/modules/analysis/stempel/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/modules/benchmark/pom.xml.templateindex 8048369eb99,75fb30467f8..21b0c1a5ad0--- a/dev-tools/maven/modules/benchmark/pom.xml.template+++ b/dev-tools/maven/modules/benchmark/pom.xml.template@@@ -43,9 -43,8 +43,8 @@@</dependency><dependency><groupId>${project.groupId}</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/solr/contrib/analysis-extras/pom.xml.templateindex ff4e14d7aba,ee6c8392384..c0a618e9158--- a/dev-tools/maven/solr/contrib/analysis-extras/pom.xml.template+++ b/dev-tools/maven/solr/contrib/analysis-extras/pom.xml.template@@@ -76,9 -76,8 +76,8 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/solr/contrib/clustering/pom.xml.templateindex 18afe9e58e2,8a10434de47..0eecf6d4401--- a/dev-tools/maven/solr/contrib/clustering/pom.xml.template+++ b/dev-tools/maven/solr/contrib/clustering/pom.xml.template@@@ -61,11 -61,15 +61,15 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency>+ <dependency>+ <groupId>javax.servlet</groupId>+ <artifactId>servlet-api</artifactId>+ <scope>provided</scope>+ </dependency><dependency><groupId>org.carrot2</groupId><artifactId>carrot2-core</artifactId>diff --cc dev-tools/maven/solr/contrib/dataimporthandler/src/extras/pom.xml.templateindex 6a93cfb2102,20de6cbf843..75899714d70--- a/dev-tools/maven/solr/contrib/dataimporthandler/src/extras/pom.xml.template+++ b/dev-tools/maven/solr/contrib/dataimporthandler/src/extras/pom.xml.template@@@ -68,9 -68,8 +68,8 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/solr/contrib/dataimporthandler/src/pom.xml.templateindex ccf9242c062,ba247a354b2..aec46df210a--- a/dev-tools/maven/solr/contrib/dataimporthandler/src/pom.xml.template+++ b/dev-tools/maven/solr/contrib/dataimporthandler/src/pom.xml.template@@@ -61,11 -61,15 +61,15 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency>+ <dependency>+ <groupId>javax.servlet</groupId>+ <artifactId>servlet-api</artifactId>+ <scope>provided</scope>+ </dependency><dependency><groupId>org.apache.geronimo.specs</groupId><artifactId>geronimo-stax-api_1.0_spec</artifactId>diff --cc dev-tools/maven/solr/contrib/extraction/pom.xml.templateindex 8bd83173f7c,e1a2581ff17..95630a91657--- a/dev-tools/maven/solr/contrib/extraction/pom.xml.template+++ b/dev-tools/maven/solr/contrib/extraction/pom.xml.template@@@ -64,9 -64,8 +64,8 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/solr/src/pom.xml.templateindex df9bb5025ff,2457615a103..7e6feb65a97--- a/dev-tools/maven/solr/src/pom.xml.template+++ b/dev-tools/maven/solr/src/pom.xml.template@@@ -48,9 -48,8 +48,8 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc dev-tools/maven/solr/src/solrj/pom.xml.templateindex dcf961b2dbe,a0d67ebbdb9..1adcd9fb28d--- a/dev-tools/maven/solr/src/solrj/pom.xml.template+++ b/dev-tools/maven/solr/src/solrj/pom.xml.template@@@ -44,9 -44,8 +44,8 @@@</dependency><dependency><groupId>org.apache.lucene</groupId>- <artifactId>lucene-test-framework</artifactId>+ <artifactId>lucene-core</artifactId><version>${project.version}</version>- <type>test-jar</type><scope>test</scope></dependency><dependency>diff --cc lucene/src/java/org/apache/lucene/index/DocFieldProcessor.javaindex 5ca6ba2f0d6,6416f518983..f4ebdc6d02f--- a/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java+++ b/lucene/src/java/org/apache/lucene/index/DocFieldProcessor.java@@@ -112,214 -73,8 +105,214 @@@ final class DocFieldProcessor extends Dreturn consumer.freeRAM();}+ public Collection<DocFieldConsumerPerField> fields() {+ Collection<DocFieldConsumerPerField> fields = new HashSet<DocFieldConsumerPerField>();+ for(int i=0;i<fieldHash.length;i++) {+ DocFieldProcessorPerField field = fieldHash[i];+ while(field != null) {+ fields.add(field.consumer);+ field = field.next;+ }+ }+ assert fields.size() == totalFieldCount;+ return fields;+ }++ /** In flush we reset the fieldHash to not maintain per-field state+ * across segments */@Override- public DocConsumerPerThread addThread(DocumentsWriterThreadState threadState) throws IOException {- return new DocFieldProcessorPerThread(threadState, this);+ void doAfterFlush() {+ fieldHash = new DocFieldProcessorPerField[2];+ hashMask = 1;+ totalFieldCount = 0;+ }++ private void rehash() {+ final int newHashSize = (fieldHash.length*2);+ assert newHashSize > fieldHash.length;++ final DocFieldProcessorPerField newHashArray[] = new DocFieldProcessorPerField[newHashSize];++ // Rehash+ int newHashMask = newHashSize-1;+ for(int j=0;j<fieldHash.length;j++) {+ DocFieldProcessorPerField fp0 = fieldHash[j];+ while(fp0 != null) {+ final int hashPos2 = fp0.fieldInfo.name.hashCode() & newHashMask;+ DocFieldProcessorPerField nextFP0 = fp0.next;+ fp0.next = newHashArray[hashPos2];+ newHashArray[hashPos2] = fp0;+ fp0 = nextFP0;+ }+ }++ fieldHash = newHashArray;+ hashMask = newHashMask;+ }++ @Override+ public void processDocument(FieldInfos fieldInfos) throws IOException {++ consumer.startDocument();+ fieldsWriter.startDocument();++ final Document doc = docState.doc;++ fieldCount = 0;++ final int thisFieldGen = fieldGen++;++ final List<Fieldable> docFields = doc.getFields();+ final int numDocFields = docFields.size();++ // Absorb any new fields first seen in this document.+ // Also absorb any changes to fields we had already+ // seen before (eg suddenly turning on norms or+ // vectors, etc.):++ for(int i=0;i<numDocFields;i++) {+ Fieldable field = docFields.get(i);+ final String fieldName = field.name();++ // Make sure we have a PerField allocated+ final int hashPos = fieldName.hashCode() & hashMask;+ DocFieldProcessorPerField fp = fieldHash[hashPos];+ while(fp != null && !fp.fieldInfo.name.equals(fieldName)) {+ fp = fp.next;+ }++ if (fp == null) {++ // TODO FI: we need to genericize the "flags" that a+ // field holds, and, how these flags are merged; it+ // needs to be more "pluggable" such that if I want+ // to have a new "thing" my Fields can do, I can+ // easily add it- FieldInfo fi = fieldInfos.add(fieldName, field.isIndexed(), field.isTermVectorStored(),++ FieldInfo fi = fieldInfos.addOrUpdate(fieldName, field.isIndexed(), field.isTermVectorStored(),+ field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),+ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());++ fp = new DocFieldProcessorPerField(this, fi);+ fp.next = fieldHash[hashPos];+ fieldHash[hashPos] = fp;+ totalFieldCount++;++ if (totalFieldCount >= fieldHash.length/2)+ rehash();+ } else {- fp.fieldInfo.update(field.isIndexed(), field.isTermVectorStored(),++ fieldInfos.addOrUpdate(fp.fieldInfo.name, field.isIndexed(), field.isTermVectorStored(),+ field.isStorePositionWithTermVector(), field.isStoreOffsetWithTermVector(),+ field.getOmitNorms(), false, field.getOmitTermFreqAndPositions());+ }++ if (thisFieldGen != fp.lastGen) {++ // First time we're seeing this field for this doc+ fp.fieldCount = 0;++ if (fieldCount == fields.length) {+ final int newSize = fields.length*2;+ DocFieldProcessorPerField newArray[] = new DocFieldProcessorPerField[newSize];+ System.arraycopy(fields, 0, newArray, 0, fieldCount);+ fields = newArray;+ }++ fields[fieldCount++] = fp;+ fp.lastGen = thisFieldGen;+ }++ fp.addField(field);++ if (field.isStored()) {+ fieldsWriter.addField(field, fp.fieldInfo);+ }+ }++ // If we are writing vectors then we must visit+ // fields in sorted order so they are written in+ // sorted order. TODO: we actually only need to+ // sort the subset of fields that have vectors+ // enabled; we could save [small amount of] CPU+ // here.+ quickSort(fields, 0, fieldCount-1);++ for(int i=0;i<fieldCount;i++)+ fields[i].consumer.processFields(fields[i].fields, fields[i].fieldCount);++ if (docState.maxTermPrefix != null && docState.infoStream != null) {+ docState.infoStream.println("WARNING: document contains at least one immense term (whose UTF8 encoding is longer than the max length " + DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8 + "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '" + docState.maxTermPrefix + "...'");+ docState.maxTermPrefix = null;+ }+ }++ @Override+ void finishDocument() throws IOException {+ try {+ fieldsWriter.finishDocument();+ } finally {+ consumer.finishDocument();+ }+ }+++ void quickSort(DocFieldProcessorPerField[] array, int lo, int hi) {+ if (lo >= hi)+ return;+ else if (hi == 1+lo) {+ if (array[lo].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) {+ final DocFieldProcessorPerField tmp = array[lo];+ array[lo] = array[hi];+ array[hi] = tmp;+ }+ return;+ }++ int mid = (lo + hi) >>> 1;++ if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp = array[lo];+ array[lo] = array[mid];+ array[mid] = tmp;+ }++ if (array[mid].fieldInfo.name.compareTo(array[hi].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp = array[mid];+ array[mid] = array[hi];+ array[hi] = tmp;++ if (array[lo].fieldInfo.name.compareTo(array[mid].fieldInfo.name) > 0) {+ DocFieldProcessorPerField tmp2 = array[lo];+ array[lo] = array[mid];+ array[mid] = tmp2;+ }+ }++ int left = lo + 1;+ int right = hi - 1;++ if (left >= right)+ return;++ DocFieldProcessorPerField partition = array[mid];++ for (; ;) {+ while (array[right].fieldInfo.name.compareTo(partition.fieldInfo.name) > 0)+ --right;++ while (left < right && array[left].fieldInfo.name.compareTo(partition.fieldInfo.name) <= 0)+ ++left;++ if (left < right) {+ DocFieldProcessorPerField tmp = array[left];+ array[left] = array[right];+ array[right] = tmp;+ --right;+ } else {+ break;+ }+ }++ quickSort(array, lo, left);+ quickSort(array, left + 1, hi);}}diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriter.javaindex a0b1ed91ce1,196a1d8fc42..09d33292023--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java@@@ -27,9 -29,6 +27,10 @@@ import java.util.concurrent.atomic.Atomimport org.apache.lucene.analysis.Analyzer;import org.apache.lucene.document.Document;+import org.apache.lucene.index.DocumentsWriterPerThread.FlushedSegment;+import org.apache.lucene.index.DocumentsWriterPerThread.IndexingChain;+import org.apache.lucene.index.DocumentsWriterPerThreadPool.ThreadState;++import org.apache.lucene.index.FieldInfos.FieldNumberBiMap;import org.apache.lucene.search.Query;import org.apache.lucene.search.SimilarityProvider;import org.apache.lucene.store.AlreadyClosedException;@@@ -112,84 -131,203 +113,78 @@@ final class DocumentsWriterPrintStream infoStream;SimilarityProvider similarityProvider;- // max # simultaneous threads; if there are more than- // this, they wait for others to finish first- private final int maxThreadStates;-- // TODO: cutover to BytesRefHash- // Deletes for our still-in-RAM (to be flushed next) segment- private BufferedDeletes pendingDeletes = new BufferedDeletes(false);-- static class DocState {- DocumentsWriter docWriter;- Analyzer analyzer;- PrintStream infoStream;- SimilarityProvider similarityProvider;- int docID;- Document doc;- String maxTermPrefix;-- // Only called by asserts- public boolean testPoint(String name) {- return docWriter.writer.testPoint(name);- }-- public void clear() {- // don't hold onto doc nor analyzer, in case it is- // largish:- doc = null;- analyzer = null;- }- }-- /** Consumer returns this on each doc. This holds any- * state that must be flushed synchronized "in docID- * order". We gather these and flush them in order. */- abstract static class DocWriter {- DocWriter next;- int docID;- abstract void finish() throws IOException;- abstract void abort();- abstract long sizeInBytes();-- void setNext(DocWriter next) {- this.next = next;- }- }-- /**- * Create and return a new DocWriterBuffer.- */- PerDocBuffer newPerDocBuffer() {- return new PerDocBuffer();- }-- /**- * RAMFile buffer for DocWriters.- */- class PerDocBuffer extends RAMFile {-- /**- * Allocate bytes used from shared pool.- */- @Override- protected byte[] newBuffer(int size) {- assert size == PER_DOC_BLOCK_SIZE;- return perDocAllocator.getByteBlock();- }-- /**- * Recycle the bytes used.- */- synchronized void recycle() {- if (buffers.size() > 0) {- setLength(0);-- // Recycle the blocks- perDocAllocator.recycleByteBlocks(buffers);- buffers.clear();- sizeInBytes = 0;-- assert numBuffers() == 0;- }- }- }-- /**- * The IndexingChain must define the {@link #getChain(DocumentsWriter)} method- * which returns the DocConsumer that the DocumentsWriter calls to process the- * documents.- */- abstract static class IndexingChain {- abstract DocConsumer getChain(DocumentsWriter documentsWriter);- }-- static final IndexingChain defaultIndexingChain = new IndexingChain() {-- @Override- DocConsumer getChain(DocumentsWriter documentsWriter) {- /*- This is the current indexing chain:-- DocConsumer / DocConsumerPerThread- --> code: DocFieldProcessor / DocFieldProcessorPerThread- --> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField- --> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField- --> code: DocInverter / DocInverterPerThread / DocInverterPerField- --> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField- --> code: TermsHash / TermsHashPerThread / TermsHashPerField- --> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField- --> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField- --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField- --> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField- --> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField- --> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField- */-- // Build up indexing chain:-- final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(documentsWriter);- final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter();- /*- * nesting TermsHash instances here to allow the secondary (TermVectors) share the interned postings- * via a shared ByteBlockPool. See TermsHashPerField for details.- */- final TermsHash termVectorsTermHash = new TermsHash(documentsWriter, false, termVectorsWriter, null);- final InvertedDocConsumer termsHash = new TermsHash(documentsWriter, true, freqProxWriter, termVectorsTermHash);- final NormsWriter normsWriter = new NormsWriter();- final DocInverter docInverter = new DocInverter(termsHash, normsWriter);- return new DocFieldProcessor(documentsWriter, docInverter);- }- };+ List<String> newFiles;- final DocConsumer consumer;+ final IndexWriter indexWriter;- // How much RAM we can use before flushing. This is 0 if- // we are flushing by doc count instead.+ private AtomicInteger numDocsInRAM = new AtomicInteger(0);+ private AtomicLong ramUsed = new AtomicLong(0);- // How much RAM we can use before flushing. This is 0 if- // we are flushing by doc count instead.- private long ramBufferSize = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024);-- // Flush @ this number of docs. If ramBufferSize is- // non-zero we will flush by RAM usage instead.- private int maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS;-+ final BufferedDeletesStream bufferedDeletesStream;+ // TODO: cutover to BytesRefHash+ private BufferedDeletes pendingDeletes = new BufferedDeletes(false);+ final IndexingChain chain;+ private final IndexWriterConfig config;- private boolean closed;- private FieldInfos fieldInfos;-- private final BufferedDeletesStream bufferedDeletesStream;- private final IndexWriter.FlushControl flushControl;-- DocumentsWriter(IndexWriterConfig config, Directory directory, IndexWriter writer, IndexingChain indexingChain, FieldInfos fieldInfos,+ final DocumentsWriterPerThreadPool perThreadPool;-- DocumentsWriter(Directory directory, IndexWriter writer, IndexingChain chain, DocumentsWriterPerThreadPool indexerThreadPool, FieldInfos fieldInfos, BufferedDeletesStream bufferedDeletesStream) throws IOException {++ DocumentsWriter(IndexWriterConfig config, Directory directory, IndexWriter writer, FieldNumberBiMap globalFieldNumbers,+ BufferedDeletesStream bufferedDeletesStream) throws IOException {this.directory = directory;- this.writer = writer;- this.similarityProvider = config.getSimilarityProvider();- this.maxThreadStates = config.getMaxThreadStates();- this.fieldInfos = fieldInfos;+ this.indexWriter = writer;+ this.similarityProvider = writer.getConfig().getSimilarityProvider();this.bufferedDeletesStream = bufferedDeletesStream;- this.perThreadPool = indexerThreadPool;- this.chain = chain;- this.perThreadPool.initialize(this, fieldInfos);- flushControl = writer.flushControl;- consumer = config.getIndexingChain().getChain(this);++ this.perThreadPool = config.getIndexerThreadPool();++ this.chain = config.getIndexingChain();++ this.perThreadPool.initialize(this, globalFieldNumbers, config);+ this.config = config;}- // Buffer a specific docID for deletion. Currently only- // used when we hit a exception when adding a document- synchronized void deleteDocID(int docIDUpto) {- pendingDeletes.addDocID(docIDUpto);- // NOTE: we do not trigger flush here. This is- // potentially a RAM leak, if you have an app that tries- // to add docs but every single doc always hits a- // non-aborting exception. Allowing a flush here gets- // very messy because we are only invoked when handling- // exceptions so to do this properly, while handling an- // exception we'd have to go off and flush new deletes- // which is risky (likely would hit some other- // confounding exception).- }-- boolean deleteQueries(Query... queries) {- final boolean doFlush = flushControl.waitUpdate(0, queries.length);+ boolean deleteQueries(final Query... queries) throws IOException {synchronized(this) {for (Query query : queries) {- pendingDeletes.addQuery(query, numDocs);+ pendingDeletes.addQuery(query, BufferedDeletes.MAX_INT);}}- return doFlush;- }-- boolean deleteQuery(Query query) {- final boolean doFlush = flushControl.waitUpdate(0, 1);- synchronized(this) {- pendingDeletes.addQuery(query, numDocs);++ Iterator<ThreadState> threadsIterator = perThreadPool.getActivePerThreadsIterator();++ while (threadsIterator.hasNext()) {+ ThreadState state = threadsIterator.next();+ state.lock();+ try {+ state.perThread.deleteQueries(queries);+ } finally {+ state.unlock();+ }}- return doFlush;++ return false;}-- boolean deleteTerms(Term... terms) {- final boolean doFlush = flushControl.waitUpdate(0, terms.length);++ boolean deleteQuery(final Query query) throws IOException {+ return deleteQueries(query);+ }++ boolean deleteTerms(final Term... terms) throws IOException {synchronized(this) {for (Term term : terms) {- pendingDeletes.addTerm(term, numDocs);+ pendingDeletes.addTerm(term, BufferedDeletes.MAX_INT);+ }+ }++ Iterator<ThreadState> threadsIterator = perThreadPool.getActivePerThreadsIterator();++ while (threadsIterator.hasNext()) {+ ThreadState state = threadsIterator.next();+ state.lock();+ try {+ state.perThread.deleteTerms(terms);+ } finally {+ state.unlock();}}- return doFlush;++ return false;}// TODO: we could check w/ FreqProxTermsWriter: if the@@@ -223,58 -345,19 +218,31 @@@* here. */synchronized void setInfoStream(PrintStream infoStream) {this.infoStream = infoStream;- for(int i=0;i<threadStates.length;i++) {- threadStates[i].docState.infoStream = infoStream;- }+ pushConfigChange();}- /** Get current segment name we are writing. */- synchronized String getSegment() {- return segment;+ synchronized void setSimilarityProvider(SimilarityProvider similarityProvider) {+ this.similarityProvider = similarityProvider;+ pushConfigChange();+ }++ private final void pushConfigChange() {+ Iterator<ThreadState> it = perThreadPool.getAllPerThreadsIterator();+ while (it.hasNext()) {+ DocumentsWriterPerThread perThread = it.next().perThread;+ perThread.docState.infoStream = this.infoStream;+ perThread.docState.similarityProvider = this.similarityProvider;+ }}- /** Set how much RAM we can use before flushing. */- synchronized void setRAMBufferSizeMB(double mb) {- if (mb == IndexWriterConfig.DISABLE_AUTO_FLUSH) {- ramBufferSize = IndexWriterConfig.DISABLE_AUTO_FLUSH;- } else {- ramBufferSize = (long) (mb*1024*1024);- }- }-- synchronized double getRAMBufferSizeMB() {- if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH) {- return ramBufferSize;- } else {- return ramBufferSize/1024./1024.;- }- }-- /** Set max buffered docs, which means we will flush by- * doc count instead of by RAM usage. */- void setMaxBufferedDocs(int count) {- maxBufferedDocs = count;- }-- int getMaxBufferedDocs() {- return maxBufferedDocs;- }-/** Returns how many docs are currently buffered in RAM. */- synchronized int getNumDocs() {- return numDocs;+ int getNumDocs() {+ return numDocsInRAM.get();+ }+ private Collection<String> abortedFiles; // List of files that were written before last abort()++ Collection<String> abortedFiles() {+ return abortedFiles;}void message(String message) {@@@ -353,96 -496,552 +321,97 @@@public boolean anyDeletions() {return pendingDeletes.any();- }-- /** Flush all pending docs to a new segment */- // Lock order: IW -> DW- synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {-- final long startTime = System.currentTimeMillis();-- // We change writer's segmentInfos:- assert Thread.holdsLock(writer);-- waitIdle();-- if (numDocs == 0) {- // nothing to do!- if (infoStream != null) {- message("flush: no docs; skipping");- }- // Lock order: IW -> DW -> BD- pushDeletes(null, segmentInfos);- return null;- }-- if (aborting) {- if (infoStream != null) {- message("flush: skip because aborting is set");- }- return null;- }-- boolean success = false;-- SegmentInfo newSegment;-- try {- assert nextDocID == numDocs;- assert waitQueue.numWaiting == 0;- assert waitQueue.waitingBytes == 0;-- if (infoStream != null) {- message("flush postings as segment " + segment + " numDocs=" + numDocs);- }-- final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,- numDocs, writer.getConfig().getTermIndexInterval(),- fieldInfos.buildSegmentCodecs(true),- pendingDeletes);- // Apply delete-by-docID now (delete-byDocID only- // happens when an exception is hit processing that- // doc, eg if analyzer has some problem w/ the text):- if (pendingDeletes.docIDs.size() > 0) {- flushState.deletedDocs = new BitVector(numDocs);- for(int delDocID : pendingDeletes.docIDs) {- flushState.deletedDocs.set(delDocID);- }- pendingDeletes.bytesUsed.addAndGet(-pendingDeletes.docIDs.size() * BufferedDeletes.BYTES_PER_DEL_DOCID);- pendingDeletes.docIDs.clear();- }-- newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false, fieldInfos);-- Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();- for (DocumentsWriterThreadState threadState : threadStates) {- threads.add(threadState.consumer);- }-- double startMBUsed = bytesUsed()/1024./1024.;-- consumer.flush(threads, flushState);-- newSegment.setHasVectors(flushState.hasVectors);-- if (infoStream != null) {- message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));- if (flushState.deletedDocs != null) {- message("new segment has " + flushState.deletedDocs.count() + " deleted docs");- }- message("flushedFiles=" + newSegment.files());- message("flushed codecs=" + newSegment.getSegmentCodecs());- }-- if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {- final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);-- if (infoStream != null) {- message("flush: create compound file \"" + cfsFileName + "\"");- }-- CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);- for(String fileName : newSegment.files()) {- cfsWriter.addFile(fileName);- }- cfsWriter.close();- deleter.deleteNewFiles(newSegment.files());- newSegment.setUseCompoundFile(true);- }-- // Must write deleted docs after the CFS so we don't- // slurp the del file into CFS:- if (flushState.deletedDocs != null) {- final int delCount = flushState.deletedDocs.count();- assert delCount > 0;- newSegment.setDelCount(delCount);- newSegment.advanceDelGen();- final String delFileName = newSegment.getDelFileName();- if (infoStream != null) {- message("flush: write " + delCount + " deletes to " + delFileName);- }- boolean success2 = false;- try {- // TODO: in the NRT case it'd be better to hand- // this del vector over to the- // shortly-to-be-opened SegmentReader and let it- // carry the changes; there's no reason to use- // filesystem as intermediary here.- flushState.deletedDocs.write(directory, delFileName);- success2 = true;- } finally {- if (!success2) {- try {- directory.deleteFile(delFileName);- } catch (Throwable t) {- // suppress this so we keep throwing the- // original exception- }- }- }- }-- if (infoStream != null) {- message("flush: segment=" + newSegment);- final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.;- final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.;- message(" ramUsed=" + nf.format(startMBUsed) + " MB" +- " newFlushedSize=" + nf.format(newSegmentSize) + " MB" +- " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" +- " docs/MB=" + nf.format(numDocs / newSegmentSize) +- " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%");- }-- success = true;- } finally {- notifyAll();- if (!success) {- if (segment != null) {- deleter.refresh(segment);- }- abort();- }}- doAfterFlush();-- // Lock order: IW -> DW -> BD- pushDeletes(newSegment, segmentInfos);- if (infoStream != null) {- message("flush time " + (System.currentTimeMillis()-startTime) + " msec");- }-- return newSegment;- }-- synchronized void close() {+ void close() {closed = true;- notifyAll();- }-- /** 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);}-- 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);+ boolean updateDocument(final Document doc, final Analyzer analyzer, final Term delTerm)+ throws CorruptIndexException, IOException {+ ensureOpen();- // This call is synchronized but fast- final DocumentsWriterThreadState state = getThreadState(doc, delTerm);+ FlushedSegment newSegment = null;- final DocState docState = state.docState;- docState.doc = doc;- docState.analyzer = analyzer;-- boolean success = false;+ ThreadState perThread = perThreadPool.getAndLock(Thread.currentThread(), this, doc);try {- // This call is not synchronized and does all the- // work- final DocWriter perDoc;- try {- perDoc = state.consumer.processDocument(fieldInfos);- } finally {- docState.clear();- }+ DocumentsWriterPerThread dwpt = perThread.perThread;+ long perThreadRAMUsedBeforeAdd = dwpt.bytesUsed();+ dwpt.updateDocument(doc, analyzer, delTerm);+ numDocsInRAM.incrementAndGet();- // This call is synchronized but fast- finishDocument(state, perDoc);-- success = true;+ newSegment = finishAddDocument(dwpt, perThreadRAMUsedBeforeAdd);} 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);- }-- 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;- }- }-- // 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);- }- }- }+ perThread.unlock();}- doFlush |= flushControl.flushByRAMUsage("new document");-- return doFlush;- }-- public synchronized void waitIdle() {- while (!allThreadsIdle()) {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);- }+ // delete term from other DWPTs later, so that this thread+ // doesn't have to lock multiple DWPTs at the same time+ if (delTerm != null) {+ deleteTerm(delTerm, perThread);}- }- synchronized void waitReady(DocumentsWriterThreadState state) {- while (!closed && (!state.isIdle || aborting)) {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);- }+ if (newSegment != null) {+ finishFlushedSegment(newSegment);}- if (closed) {- throw new AlreadyClosedException("this IndexWriter is closed");+ if (newSegment != null) {+ perThreadPool.clearThreadBindings(perThread);+ return true;}- }-- /** 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();+ return false;}- }- synchronized void waitForWaitQueue() {- do {- try {- wait();- } catch (InterruptedException ie) {- throw new ThreadInterruptedException(ie);- }- } while (!waitQueue.doResume());- }-- private static class SkipDocWriter extends DocWriter {- @Override- void finish() {- }- @Override- void abort() {- }- @Override- long sizeInBytes() {- return 0;- }+ private void finishFlushedSegment(FlushedSegment newSegment) throws IOException {+ pushDeletes(newSegment);+ if (newSegment != null) {+ indexWriter.addFlushedSegment(newSegment);}- 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 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 b;- }-- long bytesUsed() {- return bytesUsed.get() + pendingDeletes.bytesUsed.get();}- /* 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;+ private final FlushedSegment finishAddDocument(DocumentsWriterPerThread perThread,+ long perThreadRAMUsedBeforeAdd) throws IOException {+ FlushedSegment newSegment = null;-- if (perThread.getNumDocsInRAM() == maxBufferedDocs) {++ final int maxBufferedDocs = config.getMaxBufferedDocs();++ if (maxBufferedDocs != IndexWriterConfig.DISABLE_AUTO_FLUSH &&++ perThread.getNumDocsInRAM() >= maxBufferedDocs) {+ newSegment = perThread.flush();}- }-- final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);- final static int PER_DOC_BLOCK_SIZE = 1024;-- final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);+ long deltaRAM = perThread.bytesUsed() - perThreadRAMUsedBeforeAdd;+ long oldValue = ramUsed.get();+ while (!ramUsed.compareAndSet(oldValue, oldValue + deltaRAM)) {+ oldValue = ramUsed.get();+ }- String toMB(long v) {- return nf.format(v/1024./1024.);+ return newSegment;}- /* 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 = bufferedDeletesStream.bytesUsed();-- final long ramBufferSize;- final double mb = config.getRAMBufferSizeMB();- if (mb == IndexWriterConfig.DISABLE_AUTO_FLUSH) {- ramBufferSize = IndexWriterConfig.DISABLE_AUTO_FLUSH;- } else {- ramBufferSize = (long) (mb*1024*1024);- }-- synchronized(this) {- if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) {- return;- }-- doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize;+ final void subtractFlushedNumDocs(int numFlushed) {+ int oldValue = numDocsInRAM.get();+ while (!numDocsInRAM.compareAndSet(oldValue, oldValue - numFlushed)) {+ oldValue = numDocsInRAM.get();}+ }- if (doBalance) {-- 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()));- }-- 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;-- final long freeLevel = (long) (0.95 * ramBufferSize);-- 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");- }- }- break;+ private synchronized void pushDeletes(FlushedSegment flushedSegment) {+ maybePushPendingDeletes();+ if (flushedSegment != null) {+ BufferedDeletes deletes = flushedSegment.segmentDeletes;+ final long delGen = bufferedDeletesStream.getNextGen();+ // Lock order: DW -> BD+ if (deletes != null && deletes.any()) {+ final FrozenBufferedDeletes packet = new FrozenBufferedDeletes(deletes, delGen);+ if (infoStream != null) {+ message("flush: push buffered deletes");}-- if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) {- byteBlockAllocator.freeBlocks(1);+ bufferedDeletesStream.push(packet);+ if (infoStream != null) {+ message("flush: delGen=" + packet.gen);}- 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)+ flushedSegment.segmentInfo.setBufferedDeletesGen(delGen);}}diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.javaindex 5b7e5d2b4d2,00000000000..d4c1f47a11cmode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java@@@ -1,405 -1,0 +1,405 @@@+package org.apache.lucene.index;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You 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.+ */++import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_MASK;+import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;++import java.io.IOException;+import java.io.PrintStream;+import java.text.NumberFormat;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.lucene.analysis.Analyzer;+import org.apache.lucene.document.Document;+import org.apache.lucene.search.Query;+import org.apache.lucene.search.SimilarityProvider;+import org.apache.lucene.store.Directory;+import org.apache.lucene.util.BitVector;+import org.apache.lucene.util.ByteBlockPool.DirectAllocator;+import org.apache.lucene.util.RamUsageEstimator;++public class DocumentsWriterPerThread {++ /**+ * The IndexingChain must define the {@link #getChain(DocumentsWriter)} method+ * which returns the DocConsumer that the DocumentsWriter calls to process the+ * documents.+ */+ abstract static class IndexingChain {+ abstract DocConsumer getChain(DocumentsWriterPerThread documentsWriterPerThread);+ }+++ static final IndexingChain defaultIndexingChain = new IndexingChain() {++ @Override+ DocConsumer getChain(DocumentsWriterPerThread documentsWriterPerThread) {+ /*+ This is the current indexing chain:++ DocConsumer / DocConsumerPerThread+ --> code: DocFieldProcessor / DocFieldProcessorPerThread+ --> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField+ --> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField+ --> code: DocInverter / DocInverterPerThread / DocInverterPerField+ --> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField+ --> code: TermsHash / TermsHashPerThread / TermsHashPerField+ --> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField+ --> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField+ --> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField+ --> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField+ --> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField+ --> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField+ */++ // Build up indexing chain:++ final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(documentsWriterPerThread);+ final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter();++ final InvertedDocConsumer termsHash = new TermsHash(documentsWriterPerThread, freqProxWriter,+ new TermsHash(documentsWriterPerThread, termVectorsWriter, null));+ final NormsWriter normsWriter = new NormsWriter();+ final DocInverter docInverter = new DocInverter(documentsWriterPerThread.docState, termsHash, normsWriter);+ return new DocFieldProcessor(documentsWriterPerThread, docInverter);+ }+ };++ // Deletes for our still-in-RAM (to be flushed next) segment+ BufferedDeletes pendingDeletes = new BufferedDeletes(false);++ static class DocState {+ final DocumentsWriterPerThread docWriter;+ Analyzer analyzer;+ PrintStream infoStream;+ SimilarityProvider similarityProvider;+ int docID;+ Document doc;+ String maxTermPrefix;++ DocState(DocumentsWriterPerThread docWriter) {+ this.docWriter = docWriter;+ }++ // Only called by asserts+ public boolean testPoint(String name) {+ return docWriter.writer.testPoint(name);+ }++ public void clear() {+ // don't hold onto doc nor analyzer, in case it is+ // largish:+ doc = null;+ analyzer = null;+ }+ }++ static class FlushedSegment {+ final SegmentInfo segmentInfo;+ final BufferedDeletes segmentDeletes;+ final BitVector deletedDocuments;++ private FlushedSegment(SegmentInfo segmentInfo,+ BufferedDeletes segmentDeletes, BitVector deletedDocuments) {+ this.segmentInfo = segmentInfo;+ this.segmentDeletes = segmentDeletes;+ this.deletedDocuments = deletedDocuments;+ }+ }++ /** Called if we hit an exception at a bad time (when+ * updating the index files) and must discard all+ * currently buffered docs. This resets our state,+ * discarding any docs added since last flush. */+ void abort() throws IOException {+ aborting = true;+ try {+ if (infoStream != null) {+ message("docWriter: now abort");+ }+ try {+ consumer.abort();+ } catch (Throwable t) {+ }++ pendingDeletes.clear();+ // Reset all postings data+ doAfterFlush();++ } finally {+ aborting = false;+ if (infoStream != null) {+ message("docWriter: done abort");+ }+ }+ }++ final DocumentsWriter parent;+ final IndexWriter writer;++ final Directory directory;+ final DocState docState;+ final DocConsumer consumer;++ String segment; // Current segment we are working on+ boolean aborting; // True if an abort is pending++ private final PrintStream infoStream;+ private int numDocsInRAM;+ private int flushedDocCount;+ SegmentWriteState flushState;++ final AtomicLong bytesUsed = new AtomicLong(0);++ private FieldInfos fieldInfos;++ public DocumentsWriterPerThread(Directory directory, DocumentsWriter parent, FieldInfos fieldInfos, IndexingChain indexingChain) {+ this.directory = directory;+ this.parent = parent;- this.fieldInfos = fieldInfos.newFieldInfosWithGlobalFieldNumberMap();++ this.fieldInfos = fieldInfos;+ this.writer = parent.indexWriter;+ this.infoStream = parent.indexWriter.getInfoStream();+ this.docState = new DocState(this);+ this.docState.similarityProvider = parent.indexWriter.getConfig().getSimilarityProvider();++ consumer = indexingChain.getChain(this);+ }++ void setAborting() {+ aborting = true;+ }++ public void updateDocument(Document doc, Analyzer analyzer, Term delTerm) throws IOException {+ assert writer.testPoint("DocumentsWriterPerThread addDocument start");+ docState.doc = doc;+ docState.analyzer = analyzer;+ docState.docID = numDocsInRAM;+ if (delTerm != null) {+ pendingDeletes.addTerm(delTerm, numDocsInRAM);+ }++ if (segment == null) {+ // this call is synchronized on IndexWriter.segmentInfos+ segment = writer.newSegmentName();+ assert numDocsInRAM == 0;+ }++ boolean success = false;+ try {+ try {+ consumer.processDocument(fieldInfos);+ } finally {+ docState.clear();+ }++ success = true;+ } finally {+ if (!success) {+ if (!aborting) {+ // mark document as deleted+ deleteDocID(docState.docID);+ numDocsInRAM++;+ } else {+ abort();+ }+ }+ }++ success = false;+ try {+ numDocsInRAM++;+ consumer.finishDocument();++ success = true;+ } finally {+ if (!success) {+ abort();+ }+ }+ }++ // Buffer a specific docID for deletion. Currently only+ // used when we hit a exception when adding a document+ void deleteDocID(int docIDUpto) {+ pendingDeletes.addDocID(docIDUpto);+ // NOTE: we do not trigger flush here. This is+ // potentially a RAM leak, if you have an app that tries+ // to add docs but every single doc always hits a+ // non-aborting exception. Allowing a flush here gets+ // very messy because we are only invoked when handling+ // exceptions so to do this properly, while handling an+ // exception we'd have to go off and flush new deletes+ // which is risky (likely would hit some other+ // confounding exception).+ }++ void deleteQueries(Query... queries) {+ if (numDocsInRAM > 0) {+ for (Query query : queries) {+ pendingDeletes.addQuery(query, numDocsInRAM);+ }+ }+ }++ void deleteTerms(Term... terms) {+ if (numDocsInRAM > 0) {+ for (Term term : terms) {+ pendingDeletes.addTerm(term, numDocsInRAM);+ }+ }+ }++ int getNumDocsInRAM() {+ return numDocsInRAM;+ }++ SegmentCodecs getCodec() {+ return flushState.segmentCodecs;+ }++ /** Reset after a flush */+ private void doAfterFlush() throws IOException {+ segment = null;+ consumer.doAfterFlush();- fieldInfos = fieldInfos.newFieldInfosWithGlobalFieldNumberMap();++ fieldInfos = new FieldInfos(fieldInfos);+ parent.subtractFlushedNumDocs(numDocsInRAM);+ numDocsInRAM = 0;+ }++ /** Flush all pending docs to a new segment */+ FlushedSegment flush() throws IOException {+ assert numDocsInRAM > 0;++ flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,+ numDocsInRAM, writer.getConfig().getTermIndexInterval(),- SegmentCodecs.build(fieldInfos, writer.codecs), pendingDeletes);++ fieldInfos.buildSegmentCodecs(true), pendingDeletes);++ // Apply delete-by-docID now (delete-byDocID only+ // happens when an exception is hit processing that+ // doc, eg if analyzer has some problem w/ the text):+ if (pendingDeletes.docIDs.size() > 0) {+ flushState.deletedDocs = new BitVector(numDocsInRAM);+ for(int delDocID : pendingDeletes.docIDs) {+ flushState.deletedDocs.set(delDocID);+ }+ pendingDeletes.bytesUsed.addAndGet(-pendingDeletes.docIDs.size() * BufferedDeletes.BYTES_PER_DEL_DOCID);+ pendingDeletes.docIDs.clear();+ }++ if (infoStream != null) {+ message("flush postings as segment " + flushState.segmentName + " numDocs=" + numDocsInRAM);+ }++ if (aborting) {+ if (infoStream != null) {+ message("flush: skip because aborting is set");+ }+ return null;+ }++ boolean success = false;++ try {+- SegmentInfo newSegment = new SegmentInfo(segment, flushState.numDocs, directory, false, flushState.segmentCodecs, fieldInfos);++ SegmentInfo newSegment = new SegmentInfo(segment, flushState.numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false, fieldInfos);+ consumer.flush(flushState);+ pendingDeletes.terms.clear();- newSegment.clearFilesCache();++ newSegment.setHasVectors(flushState.hasVectors);++ if (infoStream != null) {+ message("new segment has " + flushState.deletedDocs.count() + " deleted docs");+ message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));+ message("flushedFiles=" + newSegment.files());+ message("flushed codecs=" + newSegment.getSegmentCodecs());+ }+ flushedDocCount += flushState.numDocs;++ BufferedDeletes segmentDeletes = null;+ if (pendingDeletes.queries.isEmpty()) {+ pendingDeletes.clear();+ } else {+ segmentDeletes = pendingDeletes;+ pendingDeletes = new BufferedDeletes(false);+ }++ doAfterFlush();++ success = true;++ return new FlushedSegment(newSegment, segmentDeletes, flushState.deletedDocs);+ } finally {+ if (!success) {+ if (segment != null) {+ synchronized(parent.indexWriter) {+ parent.indexWriter.deleter.refresh(segment);+ }+ }++ abort();+ }+ }+ }++ /** Get current segment name we are writing. */+ String getSegment() {+ return segment;+ }++ long bytesUsed() {+ return bytesUsed.get();+ }++ FieldInfos getFieldInfos() {+ return fieldInfos;+ }++ void message(String message) {+ writer.message("DW: " + message);+ }++ 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;++ /* Allocate another int[] from the shared pool */+ int[] getIntBlock() {+ int[] b = new int[INT_BLOCK_SIZE];+ bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);+ return b;+ }++ final DirectAllocator byteBlockAllocator = new DirectAllocator();++ String toMB(long v) {+ return nf.format(v/1024./1024.);+ }++}diff --cc lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThreadPool.javaindex 86bc1c1cdef,00000000000..c8665bb02eamode 100644,000000..100644--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThreadPool.java+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriterPerThreadPool.java@@@ -1,78 -1,0 +1,83 @@@+package org.apache.lucene.index;++import java.util.Iterator;+import java.util.concurrent.locks.ReentrantLock;++import org.apache.lucene.document.Document;++import org.apache.lucene.index.FieldInfos.FieldNumberBiMap;++import org.apache.lucene.index.SegmentCodecs.SegmentCodecsBuilder;++import org.apache.lucene.index.codecs.CodecProvider;++public abstract class DocumentsWriterPerThreadPool {+ final static class ThreadState extends ReentrantLock {+ final DocumentsWriterPerThread perThread;++ ThreadState(DocumentsWriterPerThread perThread) {+ this.perThread = perThread;+ }+ }++ private final ThreadState[] perThreads;+ private volatile int numThreadStatesActive;++ public DocumentsWriterPerThreadPool(int maxNumPerThreads) {+ maxNumPerThreads = (maxNumPerThreads < 1) ? IndexWriterConfig.DEFAULT_MAX_THREAD_STATES : maxNumPerThreads;+ this.perThreads = new ThreadState[maxNumPerThreads];++ numThreadStatesActive = 0;+ }+- public void initialize(DocumentsWriter documentsWriter, FieldInfos fieldInfos) {++ public void initialize(DocumentsWriter documentsWriter, FieldNumberBiMap globalFieldMap, IndexWriterConfig config) {++ final CodecProvider codecProvider = config.getCodecProvider();+ for (int i = 0; i < perThreads.length; i++) {- perThreads[i] = new ThreadState(new DocumentsWriterPerThread(documentsWriter.directory, documentsWriter, fieldInfos, documentsWriter.chain));++ final FieldInfos infos = globalFieldMap.newFieldInfos(SegmentCodecsBuilder.create(codecProvider));++ perThreads[i] = new ThreadState(new DocumentsWriterPerThread(documentsWriter.directory, documentsWriter, infos, documentsWriter.chain));+ }+ }++ public int getMaxThreadStates() {+ return perThreads.length;+ }++ public synchronized ThreadState newThreadState() {+ if (numThreadStatesActive < perThreads.length) {+ ThreadState state = perThreads[numThreadStatesActive];+ numThreadStatesActive++;+ return state;+ }++ return null;+ }++ public abstract ThreadState getAndLock(Thread requestingThread, DocumentsWriter documentsWriter, Document doc);++ public abstract void clearThreadBindings(ThreadState perThread);++ public abstract void clearAllThreadBindings();++ public Iterator<ThreadState> getAllPerThreadsIterator() {+ return getPerThreadsIterator(this.perThreads.length);+ }++ public Iterator<ThreadState> getActivePerThreadsIterator() {+ return getPerThreadsIterator(this.numThreadStatesActive);+ }++ private Iterator<ThreadState> getPerThreadsIterator(final int upto) {+ return new Iterator<ThreadState>() {+ int i = 0;++ public boolean hasNext() {+ return i < upto;+ }++ public ThreadState next() {+ return perThreads[i++];+ }++ public void remove() {+ throw new UnsupportedOperationException("remove() not supported.");+ }+ };+ }+}diff --cc lucene/src/java/org/apache/lucene/index/IndexWriter.javaindex 6ae23be406a,374934bef79..7c83eb19c65--- a/lucene/src/java/org/apache/lucene/index/IndexWriter.java+++ b/lucene/src/java/org/apache/lucene/index/IndexWriter.java@@@ -35,9 -35,10 +35,11 @@@ import java.util.concurrent.ConcurrentHimport org.apache.lucene.analysis.Analyzer;import org.apache.lucene.document.Document;+import org.apache.lucene.index.DocumentsWriterPerThread.FlushedSegment;+ import org.apache.lucene.index.FieldInfos.FieldNumberBiMap;import org.apache.lucene.index.IndexWriterConfig.OpenMode;import org.apache.lucene.index.PayloadProcessorProvider.DirPayloadProcessor;+ import org.apache.lucene.index.SegmentCodecs.SegmentCodecsBuilder;import org.apache.lucene.index.codecs.CodecProvider;import org.apache.lucene.search.Query;import org.apache.lucene.store.AlreadyClosedException;@@@ -222,10 -222,10 +223,10 @@@ public class IndexWriter implements Clovolatile long pendingCommitChangeCount;final SegmentInfos segmentInfos; // the segments- final FieldInfos fieldInfos;+ final FieldNumberBiMap globalFieldNumberMap;private DocumentsWriter docWriter;- private IndexFileDeleter deleter;+ final IndexFileDeleter deleter;private Set<SegmentInfo> segmentsToOptimize = new HashSet<SegmentInfo>(); // used by optimize to note those needing optimizationprivate int optimizeMaxNumSegments;@@@ -640,10 -638,10 +639,10 @@@return sr;}}-+/*** Obtain the number of deleted docs for a pooled reader.- * If the reader isn't being pooled, the segmentInfo's+ * If the reader isn't being pooled, the segmentInfo's* delCount is returned.*/public int numDeletedDocs(SegmentInfo info) throws IOException {@@@ -726,10 -720,8 +721,8 @@@mergePolicy = conf.getMergePolicy();mergePolicy.setIndexWriter(this);mergeScheduler = conf.getMergeScheduler();- mergedSegmentWarmer = conf.getMergedSegmentWarmer();codecs = conf.getCodecProvider();-+bufferedDeletesStream = new BufferedDeletesStream(messageID);bufferedDeletesStream.setInfoStream(infoStream);poolReaders = conf.getReaderPooling();@@@ -797,9 -789,9 +790,8 @@@setRollbackSegmentInfos(segmentInfos);// start with previous field numbers, but new FieldInfos- fieldInfos = getCurrentFieldInfos();- docWriter = new DocumentsWriter(directory, this, conf.getIndexingChain(), conf.getIndexerThreadPool(),- fieldInfos.newFieldInfosWithGlobalFieldNumberMap(), bufferedDeletesStream);+ globalFieldNumberMap = segmentInfos.getOrLoadGlobalFieldNumberMap(directory);- docWriter = new DocumentsWriter(config, directory, this, conf.getIndexingChain(),- globalFieldNumberMap.newFieldInfos(SegmentCodecsBuilder.create(codecs)), bufferedDeletesStream);++ docWriter = new DocumentsWriter(config, directory, this, globalFieldNumberMap, bufferedDeletesStream);docWriter.setInfoStream(infoStream);// Default deleter (for backwards compatibility) is@@@ -891,27 -849,7 +849,7 @@@public IndexWriterConfig getConfig() {return config;}-+- /**- * If we are flushing by doc count (not by RAM usage), and- * using LogDocMergePolicy then push maxBufferedDocs down- * as its minMergeDocs, to keep backwards compatibility.- */- private void pushMaxBufferedDocs() {- if (docWriter.getMaxBufferedDocs() != IndexWriterConfig.DISABLE_AUTO_FLUSH) {- final MergePolicy mp = mergePolicy;- if (mp instanceof LogDocMergePolicy) {- LogDocMergePolicy lmp = (LogDocMergePolicy) mp;- final int maxBufferedDocs = docWriter.getMaxBufferedDocs();- if (lmp.getMinMergeDocs() != maxBufferedDocs) {- if (infoStream != null)- message("now push maxBufferedDocs " + maxBufferedDocs + " to LogDocMergePolicy");- lmp.setMinMergeDocs(maxBufferedDocs);- }- }- }- }-/** If non-null, this will be the default infoStream used* by a newly instantiated IndexWriter.* @see #setInfoStream@@@ -2351,19 -2211,24 +2281,25 @@@ensureOpen();try {+ if (infoStream != null)+ message("flush at addIndexes(IndexReader...)");+ flush(false, true);+String mergedName = newSegmentName();- SegmentMerger merger = new SegmentMerger(directory, termIndexInterval,+ SegmentMerger merger = new SegmentMerger(directory, config.getTermIndexInterval(),mergedName, null, codecs, payloadProcessorProvider,- fieldInfos.newFieldInfosWithGlobalFieldNumberMap());+ globalFieldNumberMap.newFieldInfos(SegmentCodecsBuilder.create(codecs)));-+for (IndexReader reader : readers) // add new indexesmerger.add(reader);-+int docCount = merger.merge(); // merge 'em++ final FieldInfos fieldInfos = merger.fieldInfos();SegmentInfo info = new SegmentInfo(mergedName, docCount, directory,- false, merger.getSegmentCodecs(),- merger.fieldInfos());+ false, fieldInfos.hasProx(), merger.getSegmentCodecs(),+ fieldInfos.hasVectors(),+ fieldInfos);setDiagnostics(info, "addIndexes(IndexReader...)");boolean useCompoundFile;@@@ -2851,7 -2717,7 +2787,7 @@@message("merged segment " + merge.info + " is 100% deleted" + (keepFullyDeletedSegments ? "" : "; skipping insert"));}-- final Set mergedAway = new HashSet<SegmentInfo>(merge.segments);++ final Set<SegmentInfo> mergedAway = new HashSet<SegmentInfo>(merge.segments);int segIdx = 0;int newSegIdx = 0;boolean inserted = false;@@@ -3304,8 -3169,8 +3239,8 @@@message("merge segmentCodecs=" + merger.getSegmentCodecs());message("merge store matchedCount=" + merger.getMatchedSubReaderCount() + " vs " + merge.readers.size());}- anyNonBulkMerges |= merger.getMatchedSubReaderCount() != merge.readers.size();+ anyNonBulkMerges |= merger.getAnyNonBulkMerges();-+assert mergedDocCount == totDocCount: "mergedDocCount=" + mergedDocCount + " vs " + totDocCount;// Very important to do this before opening the readerdiff --cc lucene/src/java/org/apache/lucene/index/IndexWriterConfig.javaindex 95606fcbeda,1674068491d..e6ce95dd076--- a/lucene/src/java/org/apache/lucene/index/IndexWriterConfig.java+++ b/lucene/src/java/org/apache/lucene/index/IndexWriterConfig.java@@@ -108,26 -112,25 +112,25 @@@ public final class IndexWriterConfig imreturn WRITE_LOCK_TIMEOUT;}- private Analyzer analyzer;- private IndexDeletionPolicy delPolicy;- private IndexCommit commit;- private OpenMode openMode;- private SimilarityProvider similarityProvider;- private int termIndexInterval; // TODO: this should be private to the codec, not settable here- private MergeScheduler mergeScheduler;- private long writeLockTimeout;- private int maxBufferedDeleteTerms;- private double ramBufferSizeMB;- private int maxBufferedDocs;- private IndexingChain indexingChain;- private IndexReaderWarmer mergedSegmentWarmer;- private CodecProvider codecProvider;- private MergePolicy mergePolicy;- private boolean readerPooling;- private DocumentsWriterPerThreadPool indexerThreadPool;- private int readerTermsIndexDivisor;-- // required for clone+ private final Analyzer analyzer;+ private volatile IndexDeletionPolicy delPolicy;+ private volatile IndexCommit commit;+ private volatile OpenMode openMode;+ private volatile SimilarityProvider similarityProvider;+ private volatile int termIndexInterval; // TODO: this should be private to the codec, not settable here+ private volatile MergeScheduler mergeScheduler;+ private volatile long writeLockTimeout;+ private volatile int maxBufferedDeleteTerms;+ private volatile double ramBufferSizeMB;+ private volatile int maxBufferedDocs;+ private volatile IndexingChain indexingChain;+ private volatile IndexReaderWarmer mergedSegmentWarmer;+ private volatile CodecProvider codecProvider;+ private volatile MergePolicy mergePolicy;- private volatile int maxThreadStates;++ private volatile DocumentsWriterPerThreadPool indexerThreadPool;+ private volatile boolean readerPooling;+ private volatile int readerTermsIndexDivisor;-++private Version matchVersion;/**@@@ -272,9 -281,11 +281,11 @@@* In particular, <code>numUniqueTerms/interval</code> terms are read into* memory by an IndexReader, and, on average, <code>interval/2</code> terms* must be scanned for each random term access.- *+ ** @see #DEFAULT_TERM_INDEX_INTERVAL- */+ *+ * <p>Takes effect immediately, but only applies to newly+ * flushed/merged segments. */public IndexWriterConfig setTermIndexInterval(int interval) { // TODO: this should be private to the codec, not settable herethis.termIndexInterval = interval;return this;@@@ -387,10 -403,13 +403,13 @@@* less than 2048 MB. The precise limit depends on various factors, such as* how large your documents are, how many fields have norms, etc., so it's* best to set this value comfortably under 2048.- *+ ** <p>* The default value is {@link #DEFAULT_RAM_BUFFER_SIZE_MB}.- *+ *+ * <p>Takes effect immediately, but only the next time a+ * document is added, updated or deleted.+ ** @throws IllegalArgumentException* if ramBufferSize is enabled but non-positive, or it disables* ramBufferSize when maxBufferedDocs is already disabled@@@ -426,12 -445,15 +445,15 @@@* flush due to number of buffered documents. Note that if flushing by RAM* usage is also enabled, then the flush will be triggered by whichever comes* first.- *+ ** <p>* Disabled by default (writer flushes by RAM usage).- *+ *+ * <p>Takes effect immediately, but only the next time a+ * document is added, updated or deleted.+ ** @see #setRAMBufferSizeMB(double)- *+ ** @throws IllegalArgumentException* if maxBufferedDocs is enabled but smaller than 2, or it disables* maxBufferedDocs when ramBufferSize is already disabled@@@ -507,9 -534,10 +534,10 @@@* at once in IndexWriter. Values < 1 are invalid and if passed* <code>maxThreadStates</code> will be set to* {@link #DEFAULT_MAX_THREAD_STATES}.- */+ *+ * <p>Only takes effect when IndexWriter is first created. */- public IndexWriterConfig setMaxThreadStates(int maxThreadStates) {- this.maxThreadStates = maxThreadStates < 1 ? DEFAULT_MAX_THREAD_STATES : maxThreadStates;+ public IndexWriterConfig setIndexerThreadPool(DocumentsWriterPerThreadPool threadPool) {+ this.indexerThreadPool = threadPool;return this;}@@@ -542,12 -568,14 +572,14 @@@return readerPooling;}- /** Expert: sets the {@link DocConsumer} chain to be used to process documents. */+ /** Expert: sets the {@link DocConsumer} chain to be used to process documents.+ *+ * <p>Only takes effect when IndexWriter is first created. */IndexWriterConfig setIndexingChain(IndexingChain indexingChain) {- this.indexingChain = indexingChain == null ? DocumentsWriter.defaultIndexingChain : indexingChain;+ this.indexingChain = indexingChain == null ? DocumentsWriterPerThread.defaultIndexingChain : indexingChain;return this;}-+/** Returns the indexing chain set on {@link #setIndexingChain(IndexingChain)}. */IndexingChain getIndexingChain() {return indexingChain;diff --cc lucene/src/java/org/apache/lucene/index/NormsWriter.javaindex 398035a0c94,e0cff83de02..5064a47f3bc--- a/lucene/src/java/org/apache/lucene/index/NormsWriter.java+++ b/lucene/src/java/org/apache/lucene/index/NormsWriter.java@@@ -56,26 -93,60 +56,25 @@@ final class NormsWriter extends Inverteint normCount = 0;for (FieldInfo fi : state.fieldInfos) {- NormsWriterPerField toWrite = (NormsWriterPerField) fieldsToFlush.get(fi);-- final List<NormsWriterPerField> toMerge = byField.get(fi);++ final NormsWriterPerField toWrite = (NormsWriterPerField) fieldsToFlush.get(fi);int upto = 0;- if (toMerge != null) {-- final int numFields = toMerge.size();-+ if (toWrite != null && toWrite.upto > 0) {normCount++;- final NormsWriterPerField[] fields = new NormsWriterPerField[numFields];- int[] uptos = new int[numFields];-- for(int j=0;j<numFields;j++)- fields[j] = toMerge.get(j);-- int numLeft = numFields;-- while(numLeft > 0) {-- assert uptos[0] < fields[0].docIDs.length : " uptos[0]=" + uptos[0] + " len=" + (fields[0].docIDs.length);-- int minLoc = 0;- int minDocID = fields[0].docIDs[uptos[0]];-- for(int j=1;j<numLeft;j++) {- final int docID = fields[j].docIDs[uptos[j]];- if (docID < minDocID) {- minDocID = docID;- minLoc = j;- }- }-- assert minDocID < state.numDocs;-- // Fill hole- for(;upto<minDocID;upto++)+ int docID = 0;+ for (; docID < state.numDocs; docID++) {+ if (upto < toWrite.upto && toWrite.docIDs[upto] == docID) {+ normsOut.writeByte(toWrite.norms[upto]);+ upto++;+ } else {normsOut.writeByte((byte) 0);-- normsOut.writeByte(fields[minLoc].norms[uptos[minLoc]]);- (uptos[minLoc])++;- upto++;-- if (uptos[minLoc] == fields[minLoc].upto) {- fields[minLoc].reset();- if (minLoc != numLeft-1) {- fields[minLoc] = fields[numLeft-1];- uptos[minLoc] = uptos[numLeft-1];- }- numLeft--;}}-- // Fill final hole with defaultNorm- for(;upto<state.numDocs;upto++)- normsOut.writeByte((byte) 0);++ // we should have consumed every norm+ assert upto == toWrite.upto;++ toWrite.reset();} else if (fi.isIndexed && !fi.omitNorms) {normCount++;// Fill entire field with default norm:diff --cc lucene/src/java/org/apache/lucene/index/SegmentInfo.javaindex 45dcc6a7e5a,19c3f3844ae..81a2bab61ca--- a/lucene/src/java/org/apache/lucene/index/SegmentInfo.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentInfo.java@@@ -42,12 -42,9 +42,9 @@@ import org.apache.lucene.util.Constants*/public final class SegmentInfo {- @Deprecated- // remove with hasVector and hasProx- static final int CHECK_FIELDINFOS = -2; // hasVector and hasProx use this for bw compatibilitystatic final int NO = -1; // e.g. no norms; no deletes;static final int YES = 1; // e.g. have norms; have deletes;- static final int WITHOUT_GEN = 0; // a file name that has no GEN in it.+ static final int WITHOUT_GEN = 0; // a file name that has no GEN in it.public String name; // unique name in dirpublic int docCount; // number of docs in seg@@@ -108,9 -101,9 +101,9 @@@// NOTE: only used in-RAM by IW to track buffered deletes;// this is never written to/read from the Directoryprivate long bufferedDeletesGen;-+public SegmentInfo(String name, int docCount, Directory dir, boolean isCompoundFile,- SegmentCodecs segmentCodecs, FieldInfos fieldInfos) {+ boolean hasProx, SegmentCodecs segmentCodecs, boolean hasVectors, FieldInfos fieldInfos) {this.name = name;this.docCount = docCount;this.dir = dir;@@@ -226,21 -206,20 +208,20 @@@delCount = input.readInt();assert delCount <= docCount;- hasProx = input.readByte();+ hasProx = input.readByte() == YES;-+// System.out.println(Thread.currentThread().getName() + ": si.read hasProx=" + hasProx + " seg=" + name);- segmentCodecs = new SegmentCodecs(codecs);if (format <= DefaultSegmentInfosWriter.FORMAT_4_0) {- segmentCodecs.read(input);+ segmentCodecs = new SegmentCodecs(codecs, input);} else {// codec ID on FieldInfo is 0 so it will simply use the first codec available// TODO what todo if preflex is not available in the provider? register it or fail?- segmentCodecs.codecs = new Codec[] { codecs.lookup("PreFlex")};+ segmentCodecs = new SegmentCodecs(codecs, new Codec[] { codecs.lookup("PreFlex")});}diagnostics = input.readStringStringMap();-+if (format <= DefaultSegmentInfosWriter.FORMAT_HAS_VECTORS) {- hasVectors = input.readByte();+ hasVectors = input.readByte() == 1;} else {final String storesSegment;final String ext;@@@ -535,13 -522,18 +533,18 @@@output.writeLong(entry.getValue());}}-+output.writeByte((byte) (isCompoundFile ? YES : NO));output.writeInt(delCount);- output.writeByte((byte) hasProx);+ output.writeByte((byte) (hasProx ? 1:0));segmentCodecs.write(output);output.writeStringStringMap(diagnostics);- output.writeByte((byte) hasVectors);+ output.writeByte((byte) (hasVectors ? 1 : 0));+ }++ void setHasProx(boolean hasProx) {+ this.hasProx = hasProx;+ clearFilesCache();}public boolean getHasProx() {diff --cc lucene/src/java/org/apache/lucene/index/SegmentMerger.javaindex 6f2695ac7c0,8873029109f..67e279b3c15--- a/lucene/src/java/org/apache/lucene/index/SegmentMerger.java+++ b/lucene/src/java/org/apache/lucene/index/SegmentMerger.java@@@ -567,7 -568,12 +567,12 @@@ final class SegmentMergerint[] getDelCounts() {return mergeState.delCounts;}-++ public boolean getAnyNonBulkMerges() {+ assert matchedCount <= readers.size();+ return matchedCount != readers.size();+ }+private void mergeNorms() throws IOException {IndexOutput output = null;try {diff --cc lucene/src/java/org/apache/lucene/index/TermsHashPerField.javaindex 9d486df8d13,0b3ec241c72..ca26a8f2f26--- a/lucene/src/java/org/apache/lucene/index/TermsHashPerField.java+++ b/lucene/src/java/org/apache/lucene/index/TermsHashPerField.java@@@ -34,12 -34,12 +34,13 @@@ final class TermsHashPerField extends Ifinal TermsHashConsumerPerField consumer;+ final TermsHash termsHash;+final TermsHashPerField nextPerField;- final TermsHashPerThread perThread;- final DocumentsWriter.DocState docState;+ final DocumentsWriterPerThread.DocState docState;final FieldInvertState fieldState;TermToBytesRefAttribute termAtt;+ BytesRef termBytesRef;// Copied from our perThreadfinal IntBlockPool intPool;@@@ -52,30 -52,27 +53,27 @@@final FieldInfo fieldInfo;final BytesRefHash bytesHash;-+ParallelPostingsArray postingsArray;- private final BytesRef termBytesRef;private final AtomicLong bytesUsed;- public TermsHashPerField(DocInverterPerField docInverterPerField, final TermsHashPerThread perThread, final TermsHashPerThread nextPerThread, final FieldInfo fieldInfo) {- this.perThread = perThread;- intPool = perThread.intPool;- bytePool = perThread.bytePool;- termBytePool = perThread.termBytePool;- docState = perThread.docState;- bytesUsed = perThread.termsHash.trackAllocations?perThread.termsHash.docWriter.bytesUsed:new AtomicLong();+ public TermsHashPerField(DocInverterPerField docInverterPerField, final TermsHash termsHash, final TermsHash nextTermsHash, final FieldInfo fieldInfo) {+ intPool = termsHash.intPool;+ bytePool = termsHash.bytePool;+ termBytePool = termsHash.termBytePool;+ docState = termsHash.docState;+ this.termsHash = termsHash;+ bytesUsed = termsHash.trackAllocations?termsHash.docWriter.bytesUsed:new AtomicLong();fieldState = docInverterPerField.fieldState;- this.consumer = perThread.consumer.addField(this, fieldInfo);+ this.consumer = termsHash.consumer.addField(this, fieldInfo);PostingsBytesStartArray byteStarts = new PostingsBytesStartArray(this, bytesUsed);- bytesHash = new BytesRefHash(termBytePool, HASH_INIT_SIZE, byteStarts);+ bytesHash = new BytesRefHash(termBytePool, HASH_INIT_SIZE, byteStarts);streamCount = consumer.getStreamCount();numPostingInt = 2*streamCount;-- termBytesRef = termsHash.termBytesRef;this.fieldInfo = fieldInfo;- if (nextPerThread != null)- nextPerField = (TermsHashPerField) nextPerThread.addField(docInverterPerField, fieldInfo);+ if (nextTermsHash != null)+ nextPerField = (TermsHashPerField) nextTermsHash.addField(docInverterPerField, fieldInfo);elsenextPerField = null;}diff --cc lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.javaindex 2faf22bb011,27962632acc..4e90db27955--- a/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java+++ b/lucene/src/test-framework/org/apache/lucene/index/RandomIndexWriter.java@@@ -127,9 -147,27 +128,28 @@@ public class RandomIndexWriter implemen}public IndexReader getReader() throws IOException {- getReaderCalled = true;- if (r.nextInt(4) == 2)+++ return getReader(true);+ }++ private void doRandomOptimize() throws IOException {+ final int segCount = w.getSegmentCount();+ if (r.nextBoolean() || segCount == 0) {+ // full optimizew.optimize();+ } else {+ // partial optimize+ final int limit = _TestUtil.nextInt(r, 1, segCount);+ w.optimize(limit);+ assert w.getSegmentCount() <= limit: "limit=" + limit + " actual=" + w.getSegmentCount();+ }+ }++ public IndexReader getReader(boolean applyDeletions) throws IOException {+ getReaderCalled = true;+ if (r.nextInt(4) == 2) {+ doRandomOptimize();+ }// If we are writing with PreFlexRW, force a full// IndexReader.open so terms are sorted in codepoint// order during searching:diff --cc lucene/src/test-framework/org/apache/lucene/util/LuceneTestCase.javaindex a3214b5a906,b56aaf2e4d5..fafabad3050--- a/lucene/src/test-framework/org/apache/lucene/util/LuceneTestCase.java+++ b/lucene/src/test-framework/org/apache/lucene/util/LuceneTestCase.java@@@ -339,13 -341,15 +341,15 @@@ public abstract class LuceneTestCase exTimeZone.setDefault(timeZone);testsFailed = false;}-+@AfterClasspublic static void afterClassLuceneTestCaseJ4() {- int rogueThreads = threadCleanup("test class");- if (rogueThreads > 0) {- // TODO: fail here once the leaks are fixed.- System.err.println("RESOURCE LEAK: test class left " + rogueThreads + " thread(s) running");+ if (! "false".equals(TEST_CLEAN_THREADS)) {+ int rogueThreads = threadCleanup("test class");+ if (rogueThreads > 0) {+ // TODO: fail here once the leaks are fixed.+ System.err.println("RESOURCE LEAK: test class left " + rogueThreads + " thread(s) running");+ }}String codecDescription;CodecProvider cp = CodecProvider.getDefault();@@@ -490,10 -494,10 +494,10 @@@assertTrue("ensure your setUp() calls super.setUp()!!!", setup);setup = false;BooleanQuery.setMaxClauseCount(savedBoolMaxClauseCount);- if (!getClass().getName().startsWith("org.apache.solr")) {+ if ("perMethod".equals(TEST_CLEAN_THREADS)) {int rogueThreads = threadCleanup("test method: '" + getName() + "'");if (rogueThreads > 0) {- System.err.println("RESOURCE LEAK: test method: '" + getName()+ System.err.println("RESOURCE LEAK: test method: '" + getName()+ "' left " + rogueThreads + " thread(s) running");// TODO: fail, but print seed for now.if (!testsFailed && uncaughtExceptions.isEmpty()) {@@@ -534,10 -538,10 +538,10 @@@}}- private final static int THREAD_STOP_GRACE_MSEC = 1000;+ private final static int THREAD_STOP_GRACE_MSEC = 50;// jvm-wide list of 'rogue threads' we found, so they only get reported once.private final static IdentityHashMap<Thread,Boolean> rogueThreads = new IdentityHashMap<Thread,Boolean>();-+static {// just a hack for things like eclipse test-runner threadsfor (Thread t : Thread.getAllStackTraces().keySet()) {@@@ -898,11 -910,15 +900,17 @@@stores.put(dir, Thread.currentThread().getStackTrace());return dir;}+++ /** Returns a new field instance.+ * See {@link #newField(String, String, Field.Store, Field.Index, Field.TermVector)} for more information */public static Field newField(String name, String value, Index index) {return newField(random, name, value, index);}+++ /** Returns a new field instance.+ * See {@link #newField(String, String, Field.Store, Field.Index, Field.TermVector)} for more information */public static Field newField(String name, String value, Store store, Index index) {return newField(random, name, value, store, index);}@@@ -910,15 -935,21 +927,24 @@@public static Field newField(String name, String value, Store store, Index index, TermVector tv) {return newField(random, name, value, store, index, tv);}+++ /** Returns a new field instance, using the specified random.+ * See {@link #newField(String, String, Field.Store, Field.Index, Field.TermVector)} for more information */public static Field newField(Random random, String name, String value, Index index) {return newField(random, name, value, Store.NO, index);}+++ /** Returns a new field instance, using the specified random.+ * See {@link #newField(String, String, Field.Store, Field.Index, Field.TermVector)} for more information */public static Field newField(Random random, String name, String value, Store store, Index index) {return newField(random, name, value, store, index, TermVector.NO);}+++ /** Returns a new field instance, using the specified random.+ * See {@link #newField(String, String, Field.Store, Field.Index, Field.TermVector)} for more information */public static Field newField(Random random, String name, String value, Store store, Index index, TermVector tv) {if (!index.isIndexed())return new Field(name, value, store, index);diff --cc lucene/src/test/org/apache/lucene/index/TestAddIndexes.javaindex 725bf954c95,6085d342c17..c19beff3c4f--- a/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java+++ b/lucene/src/test/org/apache/lucene/index/TestAddIndexes.java@@@ -1045,8 -1079,8 +1079,8 @@@ public class TestAddIndexes extends LucIndexWriter w3 = new IndexWriter(dir, conf);w3.addIndexes(readers);w3.close();-- assertEquals("Only one compound segment should exist", 3, dir.listAll().length);+ // we should now see segments_X, segments.gen,_Y.cfs, _Z.fnx+ assertEquals("Only one compound segment should exist", 4, dir.listAll().length);}-+}diff --cc lucene/src/test/org/apache/lucene/index/TestDoc.javaindex c60ceb6a6d9,9deaf4b9f09..0e7586ca8d0--- a/lucene/src/test/org/apache/lucene/index/TestDoc.java+++ b/lucene/src/test/org/apache/lucene/index/TestDoc.java@@@ -202,11 -202,11 +202,11 @@@ public class TestDoc extends LuceneTestmerger.merge();r1.close();r2.close();-+ final FieldInfos fieldInfos = merger.fieldInfos();final SegmentInfo info = new SegmentInfo(merged, si1.docCount + si2.docCount, si1.dir,- false, merger.getSegmentCodecs(),- merger.fieldInfos());+ false, fieldInfos.hasProx(), merger.getSegmentCodecs(),+ fieldInfos.hasVectors(), fieldInfos);-+if (useCompoundFile) {Collection<String> filesToDelete = merger.createCompoundFile(merged + ".cfs", info);info.setUseCompoundFile(true);diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriter.javaindex 533f1d8c30d,89bafd921d1..91e5491dca5--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriter.java@@@ -681,8 -685,124 +685,124 @@@ public class TestIndexWriter extends Ludir.close();}+ // Make sure it's OK to change RAM buffer size and+ // maxBufferedDocs in a write session+ public void testChangingRAMBuffer() throws IOException {+ Directory dir = newDirectory();+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));+ writer.getConfig().setMaxBufferedDocs(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);++ int lastFlushCount = -1;+ for(int j=1;j<52;j++) {+ Document doc = new Document();+ doc.add(new Field("field", "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));+ writer.addDocument(doc);+ _TestUtil.syncConcurrentMerges(writer);+ int flushCount = writer.getFlushCount();+ if (j == 1)+ lastFlushCount = flushCount;+ else if (j < 10)+ // No new files should be created+ assertEquals(flushCount, lastFlushCount);+ else if (10 == j) {+ assertTrue(flushCount > lastFlushCount);+ lastFlushCount = flushCount;+ writer.getConfig().setRAMBufferSizeMB(0.000001);+ writer.getConfig().setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ } else if (j < 20) {+ assertTrue(flushCount > lastFlushCount);+ lastFlushCount = flushCount;+ } else if (20 == j) {+ writer.getConfig().setRAMBufferSizeMB(16);+ writer.getConfig().setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ lastFlushCount = flushCount;+ } else if (j < 30) {+ assertEquals(flushCount, lastFlushCount);+ } else if (30 == j) {+ writer.getConfig().setRAMBufferSizeMB(0.000001);+ writer.getConfig().setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ } else if (j < 40) {+ assertTrue(flushCount> lastFlushCount);+ lastFlushCount = flushCount;+ } else if (40 == j) {+ writer.getConfig().setMaxBufferedDocs(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ lastFlushCount = flushCount;+ } else if (j < 50) {+ assertEquals(flushCount, lastFlushCount);+ writer.getConfig().setMaxBufferedDocs(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ } else if (50 == j) {+ assertTrue(flushCount > lastFlushCount);+ }+ }+ writer.close();+ dir.close();+ }++ public void testChangingRAMBuffer2() throws IOException {+ Directory dir = newDirectory();+ IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer()));+ writer.getConfig().setMaxBufferedDocs(10);+ writer.getConfig().setMaxBufferedDeleteTerms(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);++ for(int j=1;j<52;j++) {+ Document doc = new Document();+ doc.add(new Field("field", "aaa" + j, Field.Store.YES, Field.Index.ANALYZED));+ writer.addDocument(doc);+ }++ int lastFlushCount = -1;+ for(int j=1;j<52;j++) {+ writer.deleteDocuments(new Term("field", "aaa" + j));+ _TestUtil.syncConcurrentMerges(writer);+ int flushCount = writer.getFlushCount();+ if (j == 1)+ lastFlushCount = flushCount;+ else if (j < 10) {+ // No new files should be created+ assertEquals(flushCount, lastFlushCount);+ } else if (10 == j) {+ assertTrue(flushCount > lastFlushCount);+ lastFlushCount = flushCount;+ writer.getConfig().setRAMBufferSizeMB(0.000001);+ writer.getConfig().setMaxBufferedDeleteTerms(1);+ } else if (j < 20) {+ assertTrue(flushCount > lastFlushCount);+ lastFlushCount = flushCount;+ } else if (20 == j) {+ writer.getConfig().setRAMBufferSizeMB(16);+ writer.getConfig().setMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ lastFlushCount = flushCount;+ } else if (j < 30) {+ assertEquals(flushCount, lastFlushCount);+ } else if (30 == j) {+ writer.getConfig().setRAMBufferSizeMB(0.000001);+ writer.getConfig().setMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ writer.getConfig().setMaxBufferedDeleteTerms(1);+ } else if (j < 40) {+ assertTrue(flushCount> lastFlushCount);+ lastFlushCount = flushCount;+ } else if (40 == j) {+ writer.getConfig().setMaxBufferedDeleteTerms(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ lastFlushCount = flushCount;+ } else if (j < 50) {+ assertEquals(flushCount, lastFlushCount);+ writer.getConfig().setMaxBufferedDeleteTerms(10);+ writer.getConfig().setRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH);+ } else if (50 == j) {+ assertTrue(flushCount > lastFlushCount);+ }+ }+ writer.close();+ dir.close();+ }+public void testDiverseDocs() throws IOException {- MockDirectoryWrapper dir = newDirectory();+ MockDirectoryWrapper dir = newDirectory();IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setRAMBufferSizeMB(0.5));for(int i=0;i<3;i++) {// First, docs where every term is unique (heavy on@@@ -2912,4 -3032,123 +3032,123 @@@w.close();dir.close();}++ private static class StringSplitAnalyzer extends Analyzer {+ @Override+ public TokenStream tokenStream(String fieldName, Reader reader) {+ return new StringSplitTokenizer(reader);+ }+ }++ private static class StringSplitTokenizer extends Tokenizer {+ private final String[] tokens;+ private int upto = 0;+ private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);++ public StringSplitTokenizer(Reader r) {+ try {+ final StringBuilder b = new StringBuilder();+ final char[] buffer = new char[1024];+ int n;+ while((n = r.read(buffer)) != -1) {+ b.append(buffer, 0, n);+ }+ tokens = b.toString().split(" ");+ } catch (IOException ioe) {+ throw new RuntimeException(ioe);+ }+ }++ @Override+ public final boolean incrementToken() throws IOException {+ clearAttributes();+ if (upto < tokens.length) {+ termAtt.setEmpty();+ termAtt.append(tokens[upto]);+ upto++;+ return true;+ } else {+ return false;+ }+ }+ }++ /**+ * Make sure we skip wicked long terms.+ */+ public void testWickedLongTerm() throws IOException {+ Directory dir = newDirectory();+ RandomIndexWriter w = new RandomIndexWriter(random, dir, new StringSplitAnalyzer());+- char[] chars = new char[DocumentsWriter.MAX_TERM_LENGTH_UTF8];++ char[] chars = new char[DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8];+ Arrays.fill(chars, 'x');+ Document doc = new Document();+ final String bigTerm = new String(chars);+ final BytesRef bigTermBytesRef = new BytesRef(bigTerm);++ // This contents produces a too-long term:+ String contents = "abc xyz x" + bigTerm + " another term";+ doc.add(new Field("content", contents, Field.Store.NO, Field.Index.ANALYZED));+ w.addDocument(doc);++ // Make sure we can add another normal document+ doc = new Document();+ doc.add(new Field("content", "abc bbb ccc", Field.Store.NO, Field.Index.ANALYZED));+ w.addDocument(doc);++ IndexReader reader = w.getReader();+ w.close();++ // Make sure all terms < max size were indexed+ assertEquals(2, reader.docFreq(new Term("content", "abc")));+ assertEquals(1, reader.docFreq(new Term("content", "bbb")));+ assertEquals(1, reader.docFreq(new Term("content", "term")));+ assertEquals(1, reader.docFreq(new Term("content", "another")));++ // Make sure position is still incremented when+ // massive term is skipped:+ DocsAndPositionsEnum tps = MultiFields.getTermPositionsEnum(reader, null, "content", new BytesRef("another"));+ assertEquals(0, tps.nextDoc());+ assertEquals(1, tps.freq());+ assertEquals(3, tps.nextPosition());++ // Make sure the doc that has the massive term is in+ // the index:+ assertEquals("document with wicked long term should is not in the index!", 2, reader.numDocs());++ reader.close();+ dir.close();+ dir = newDirectory();++ // Make sure we can add a document with exactly the+ // maximum length term, and search on that term:+ doc = new Document();+ Field contentField = new Field("content", "", Field.Store.NO, Field.Index.NOT_ANALYZED);+ doc.add(contentField);++ w = new RandomIndexWriter(random, dir);++ contentField.setValue("other");+ w.addDocument(doc);++ contentField.setValue("term");+ w.addDocument(doc);++ contentField.setValue(bigTerm);+ w.addDocument(doc);++ contentField.setValue("zzz");+ w.addDocument(doc);++ reader = w.getReader();+ w.close();+ assertEquals(1, reader.docFreq(new Term("content", bigTerm)));++ FieldCache.DocTermsIndex dti = FieldCache.DEFAULT.getTermsIndex(reader, "content", random.nextBoolean());+ assertEquals(5, dti.numOrd()); // +1 for null ord+ assertEquals(4, dti.size());+ assertEquals(bigTermBytesRef, dti.lookup(3, new BytesRef()));+ reader.close();+ dir.close();+ }}diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.javaindex 527847b2167,587e8709698..3052dab7fcf--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterConfig.java@@@ -24,19 -24,19 +24,19 @@@ import java.util.HashSetimport java.util.Set;import org.apache.lucene.analysis.MockAnalyzer;-import org.apache.lucene.index.DocumentsWriter.IndexingChain;+import org.apache.lucene.index.DocumentsWriterPerThread.IndexingChain;import org.apache.lucene.index.IndexWriterConfig.OpenMode;- import org.apache.lucene.search.DefaultSimilarity;+ import org.apache.lucene.search.DefaultSimilarityProvider;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.util.LuceneTestCase;import org.junit.Test;public class TestIndexWriterConfig extends LuceneTestCase {- private static final class MySimilarity extends DefaultSimilarity {+ private static final class MySimilarityProvider extends DefaultSimilarityProvider {// Does not implement anything - used only for type checking on IndexWriterConfig.}-+private static final class MyIndexingChain extends IndexingChain {// Does not implement anything - used only for type checking on IndexWriterConfig.diff --cc lucene/src/test/org/apache/lucene/index/TestIndexWriterExceptions.javaindex 686ed49fab1,88bcd50fbf3..b20a195446d--- a/lucene/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java+++ b/lucene/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java@@@ -792,10 -792,19 +793,19 @@@ public class TestIndexWriterExceptionsreader.close();dir.close();}-+private static class FailOnlyInCommit extends MockDirectoryWrapper.Failure {- boolean fail1, fail2;+ boolean failOnCommit, failOnDeleteFile;+ private final boolean dontFailDuringGlobalFieldMap;+ private static final String PREPARE_STAGE = "prepareCommit";+ private static final String FINISH_STAGE = "finishCommit";+ private final String stage;++ public FailOnlyInCommit(boolean dontFailDuringGlobalFieldMap, String stage) {+ this.dontFailDuringGlobalFieldMap = dontFailDuringGlobalFieldMap;+ this.stage = stage;+ }@Overridepublic void eval(MockDirectoryWrapper dir) throws IOException {@@@ -820,30 -835,41 +836,41 @@@}}}-+- // LUCENE-1214public void testExceptionsDuringCommit() throws Throwable {- MockDirectoryWrapper dir = newDirectory();- FailOnlyInCommit failure = new FailOnlyInCommit();- IndexWriter w = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()));- Document doc = new Document();- doc.add(newField("field", "a field", Field.Store.YES,- Field.Index.ANALYZED));- w.addDocument(doc);- dir.failOn(failure);- try {- w.close();- fail();- } catch (IOException ioe) {- fail("expected only RuntimeException");- } catch (RuntimeException re) {- // Expected+ FailOnlyInCommit[] failures = new FailOnlyInCommit[] {+ // LUCENE-1214+ new FailOnlyInCommit(false, FailOnlyInCommit.PREPARE_STAGE), // fail during global field map is written+ new FailOnlyInCommit(true, FailOnlyInCommit.PREPARE_STAGE), // fail after global field map is written+ new FailOnlyInCommit(false, FailOnlyInCommit.FINISH_STAGE) // fail while running finishCommit+ };++ for (FailOnlyInCommit failure : failures) {+ MockDirectoryWrapper dir = newDirectory();+ IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(+ TEST_VERSION_CURRENT, new MockAnalyzer()));+ Document doc = new Document();+ doc.add(newField("field", "a field", Field.Store.YES,+ Field.Index.ANALYZED));+ w.addDocument(doc);+ dir.failOn(failure);+ try {+ w.close();+ fail();+ } catch (IOException ioe) {+ fail("expected only RuntimeException");+ } catch (RuntimeException re) {+ // Expected+ }+ assertTrue(dir.fileExists("1.fnx"));+ assertTrue(failure.failOnCommit && failure.failOnDeleteFile);+ w.rollback();+ assertFalse(dir.fileExists("1.fnx"));+ // FIXME: on windows, this often fails! assertEquals(0, dir.listAll().length);+ dir.close();}- assertTrue(failure.fail1 && failure.fail2);- w.rollback();- dir.close();}-+public void testOptimizeExceptions() throws IOException {Directory startDir = newDirectory();IndexWriterConfig conf = newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer()).setMaxBufferedDocs(2).setMergePolicy(newLogMergePolicy());diff --cc lucene/src/test/org/apache/lucene/index/TestSegmentMerger.javaindex cc9cb064c81,39d8386ec90..2689cc1cde8--- a/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java+++ b/lucene/src/test/org/apache/lucene/index/TestSegmentMerger.java@@@ -78,10 -78,12 +78,11 @@@ public class TestSegmentMerger extendsmerger.add(reader2);int docsMerged = merger.merge();assertTrue(docsMerged == 2);+ final FieldInfos fieldInfos = merger.fieldInfos();//Should be able to open a new SegmentReader against the new directory- SegmentReader mergedReader = SegmentReader.get(false, mergedDir, new SegmentInfo(mergedSegment, docsMerged, mergedDir, false,- merger.getSegmentCodecs(), merger.fieldInfos()),+ SegmentReader mergedReader = SegmentReader.get(false, mergedDir, new SegmentInfo(mergedSegment, docsMerged, mergedDir, false, fieldInfos.hasProx(),+ merger.getSegmentCodecs(), fieldInfos.hasVectors(), fieldInfos),BufferedIndexInput.BUFFER_SIZE, true, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR);-assertTrue(mergedReader != null);assertTrue(mergedReader.numDocs() == 2);Document newDoc1 = mergedReader.document(0);