Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
PLEASE MAKE A BACK-UP OF YOUR COMPLETE DATA DIRECTORY BEFORE USING THIS redesign for better IO performance enhanced database seek-time by avoiding write operations at distant positions of a database file. until now, a USEDC counter was written at the head-section of a kelondroRecords database file (which is the basic data structure of all kelondro database files) to store the actual number of records that are contained in the database. Now, this value is computed from the database file size. This is either done only once at start-time, or continuously when run in asserts enabled. The counter is then updated only in RAM, and written at close of the file. If the close fails, the correct number can be computed from the file size, and if this is not equal to the stored number it is a strong evidence that YaCY was not shut down properly. To preserve consistency, the complete storage-routine had to be re-written. Another change enhances read of nodes in some cases, where the data-tail can be read together with the data-head. This saves another IO lookup during each DB node fetch. Includes also many small bugfixes. IF ANYTHING GOES WRONG, ALL YOUR DATA IS LOST: PLEASE MAKE A BACK-UP
orbiterdc0c06e43dfe
diff --git a/build.properties b/build.propertiesindex a05c9e08c..480e1f1b3 100644--- a/build.properties+++ b/build.properties@@ -3,7 +3,7 @@ javacSource=1.4javacTarget=1.4# Release Configuration-releaseVersion=0.504+releaseVersion=0.505releaseFile=yacy_dev_v${releaseVersion}_${DSTAMP}_${releaseNr}.tar.gz#releaseFile=yacy_v${releaseVersion}_${DSTAMP}_${releaseNr}.tar.gzreleaseDir=yacy_dev_v${releaseVersion}_${DSTAMP}_${releaseNr}diff --git a/htroot/CacheAdmin_p.java b/htroot/CacheAdmin_p.javaindex a477944ae..09169d3e6 100644--- a/htroot/CacheAdmin_p.java+++ b/htroot/CacheAdmin_p.java@@ -115,7 +115,7 @@ public class CacheAdmin_p {urlstr = url.toNormalform();prop.put("info_url", urlstr);- info.ensureCapacity(40000);+ info.ensureCapacity(10000);try {final IResourceInfo resInfo = switchboard.cacheManager.loadResourceInfo(url);formatHeader(prop, resInfo.getMap());diff --git a/htroot/yacy/list.java b/htroot/yacy/list.javaindex a862f309f..feaa4fc2c 100644--- a/htroot/yacy/list.java+++ b/htroot/yacy/list.java@@ -51,7 +51,6 @@// contains contributions by [FB] to support listing URLs for URL Fetcherimport java.io.File;-import java.net.InetAddress;import de.anomic.data.URLFetcherStack;import de.anomic.data.listManager;diff --git a/source/de/anomic/index/indexRAMRI.java b/source/de/anomic/index/indexRAMRI.javaindex 661d2eabb..e8cd1d2aa 100644--- a/source/de/anomic/index/indexRAMRI.java+++ b/source/de/anomic/index/indexRAMRI.java@@ -45,7 +45,6 @@ import de.anomic.kelondro.kelondroRow;import de.anomic.server.serverByteBuffer;import de.anomic.server.serverFileUtils;import de.anomic.server.logging.serverLog;-import de.anomic.server.serverMemory;import de.anomic.yacy.yacySeedDB;public final class indexRAMRI implements indexRI {@@ -111,7 +110,7 @@ public final class indexRAMRI implements indexRI {if (indexDumpFile.exists()) indexDumpFile.delete();kelondroFixedWidthArray dumpArray = null;kelondroBufferedRA writeBuffer = null;- if (serverMemory.available() > 50 * bufferStructureBasis.objectsize() * cache.size()) {+ if (false /*serverMemory.available() > 50 * bufferStructureBasis.objectsize() * cache.size()*/) {writeBuffer = new kelondroBufferedRA();dumpArray = new kelondroFixedWidthArray(writeBuffer, bufferStructureBasis, 0);log.logInfo("started dump of ram cache: " + cache.size() + " words; memory-enhanced write");@@ -151,7 +150,7 @@ public final class indexRAMRI implements indexRI {row.setCol(1, occ);row.setCol(2, time);row.setCol(3, iEntry.toKelondroEntry().bytes());- dumpArray.overwrite((int) urlcount++, row);+ dumpArray.set((int) urlcount++, row);}}wordcount++;diff --git a/source/de/anomic/kelondro/kelondroAbstractRA.java b/source/de/anomic/kelondro/kelondroAbstractRA.javaindex bf70e3f16..543b1a339 100644--- a/source/de/anomic/kelondro/kelondroAbstractRA.java+++ b/source/de/anomic/kelondro/kelondroAbstractRA.java@@ -196,37 +196,6 @@ abstract class kelondroAbstractRA implements kelondroRA {bb[bbsize++] = (byte) c;}}-/*- public void writeMap(final Map map, final String comment) throws IOException {- this.seek(0);- writeLine("# " + comment);- final Iterator iter = map.entrySet().iterator();- Map.Entry entry;- while (iter.hasNext()) {- entry = (Map.Entry) iter.next();- write(((String) entry.getKey()).getBytes());- write((byte) '=');- writeLine((String) entry.getValue());- }- writeLine("# EOF");- }-- public Map readMap() throws IOException {- this.seek(0);- final TreeMap map = new TreeMap();- String line;- int pos;- while ((line = readLine()) != null) { // very slow readLine????- line = line.trim();- if (line.equals("# EOF")) return map;- if ((line.length() == 0) || (line.charAt(0) == '#')) continue;- pos = line.indexOf("=");- if (pos < 0) continue;- map.put(line.substring(0, pos), line.substring(pos + 1));- }- return map;- }-*/public void writeMap(final Map map, final String comment) throws IOException {this.seek(0);diff --git a/source/de/anomic/kelondro/kelondroArray.java b/source/de/anomic/kelondro/kelondroArray.javaindex 3dc193f99..16994c1a1 100644--- a/source/de/anomic/kelondro/kelondroArray.java+++ b/source/de/anomic/kelondro/kelondroArray.java@@ -32,8 +32,7 @@ public interface kelondroArray {public kelondroRow row();- public kelondroRow.Entry replace(int index, kelondroRow.Entry rowentry) throws IOException;- public void overwrite(int index, kelondroRow.Entry rowentry) throws IOException;+ public void set(int index, kelondroRow.Entry rowentry) throws IOException;public kelondroRow.Entry get(int index) throws IOException;diff --git a/source/de/anomic/kelondro/kelondroCache.java b/source/de/anomic/kelondro/kelondroCache.javaindex 084ec3fb9..f42ae320d 100644--- a/source/de/anomic/kelondro/kelondroCache.java+++ b/source/de/anomic/kelondro/kelondroCache.java@@ -269,13 +269,13 @@ public class kelondroCache implements kelondroIndex {}public synchronized void close() throws IOException {- readHitCache = null;- readMissCache = null;flushUnique();flushDoubles();+ index.close();+ readHitCache = null;+ readMissCache = null;writeBufferUnique = null;writeBufferDoubles = null;- index.close();}public boolean has(byte[] key) throws IOException {diff --git a/source/de/anomic/kelondro/kelondroCollectionIndex.java b/source/de/anomic/kelondro/kelondroCollectionIndex.javaindex dd115dc81..b89a7fd1c 100644--- a/source/de/anomic/kelondro/kelondroCollectionIndex.java+++ b/source/de/anomic/kelondro/kelondroCollectionIndex.java@@ -171,7 +171,7 @@ public class kelondroCollectionIndex {// write a logif (System.currentTimeMillis() - lastlog > 30000) {- serverLog.logFine("STARTUP", "created " + count + " RWI index entries. " + (((System.currentTimeMillis() - start) * (array.USAGE.allCount() - count) / count) / 60000) + " minutes remaining for this array");+ serverLog.logFine("STARTUP", "created " + count + " RWI index entries. " + (((System.currentTimeMillis() - start) * (array.size() + array.free() - count) / count) / 60000) + " minutes remaining for this array");lastlog = System.currentTimeMillis();}}@@ -377,7 +377,7 @@ public class kelondroCollectionIndex {arrayEntry.setCol(1, collection.exportCollection());// overwrite entry in this array- array.overwrite(oldrownumber, arrayEntry);+ array.set(oldrownumber, arrayEntry);// update the index entryindexrow.setCol(idx_col_chunkcount, collection.size());diff --git a/source/de/anomic/kelondro/kelondroFixedWidthArray.java b/source/de/anomic/kelondro/kelondroFixedWidthArray.javaindex 2af2ecd9a..e5e064c20 100644--- a/source/de/anomic/kelondro/kelondroFixedWidthArray.java+++ b/source/de/anomic/kelondro/kelondroFixedWidthArray.java@@ -60,7 +60,7 @@ public class kelondroFixedWidthArray extends kelondroRecords implements kelondrosuper(file, 0, 0, thisOHBytes, thisOHHandles, rowdef, intprops, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);if (!(super.fileExisted)) {for (int i = 0; i < intprops; i++) {- setHandle(i, new Handle(0));+ setHandle(i, new Handle(NUL));}// store column descriptionfor (int i = 0; i < rowdef.columns(); i++) {@@ -97,36 +97,16 @@ public class kelondroFixedWidthArray extends kelondroRecords implements kelondro}}- public synchronized kelondroRow.Entry replace(int index, kelondroRow.Entry rowentry) throws IOException {-- // make room for element- Node n;- while (super.USAGE.allCount() <= index) {- n = newNode();- n.commit(CP_NONE);- }-- // get the node at position index- n = getNode(new Handle(index));-- // write the row- byte[] before = n.setValueRow((rowentry == null) ? null : rowentry.bytes());- n.commit(CP_NONE);-- return row().newEntry(before);- }-- public synchronized void overwrite(int index, kelondroRow.Entry rowentry) throws IOException {+ public synchronized void set(int index, kelondroRow.Entry rowentry) throws IOException {// this writes a row without reading the row from the file system first// create a node at position index with rowentryHandle h = new Handle(index);- h.adoptAllCount(); // adopt counting- newNode(h, (rowentry == null) ? null : rowentry.bytes(), 0).commit(CP_NONE);+ newNode(h, (rowentry == null) ? null : rowentry.bytes(), 0, true).commit(CP_NONE);}public synchronized kelondroRow.Entry get(int index) throws IOException {- return row().newEntry(getNode(new Handle(index)).getValueRow());+ return row().newEntry(getNode(new Handle(index), true).getValueRow());}protected synchronized int seti(int index, int value) throws IOException {@@ -141,19 +121,18 @@ public class kelondroFixedWidthArray extends kelondroRecords implements kelondropublic synchronized int add(kelondroRow.Entry rowentry) throws IOException {- Node n = newNode();- n.setValueRow(rowentry.bytes());+ Node n = newNode(rowentry.bytes());n.commit(CP_NONE);return n.handle().hashCode();}public synchronized void remove(int index) throws IOException {- if (index >= super.USAGE.allCount()) throw new IOException("remove: index " + index + " out of bounds " + super.USAGE.allCount());+ if (index >= (super.free() + super.size())) throw new IOException("remove: index " + index + " out of bounds " + (super.free() + super.size()));// get the node at position indexHandle h = new Handle(index);- Node n = getNode(h);+ Node n = getNode(h, false);// erase the rown.setValueRow(null);@@ -166,7 +145,7 @@ public class kelondroFixedWidthArray extends kelondroRecords implements kelondropublic void print() throws IOException {System.out.println("PRINTOUT of table, length=" + size());kelondroRow.Entry row;- for (int i = 0; i < super.USAGE.allCount(); i++) {+ for (int i = 0; i < (super.free() + super.size()); i++) {System.out.print("row " + i + ": ");row = get(i);for (int j = 0; j < row.columns(); j++) System.out.print(((row.empty(j)) ? "NULL" : row.getColString(j, "UTF-8")) + ", ");@@ -183,7 +162,7 @@ public class kelondroFixedWidthArray extends kelondroRecords implements kelondroSystem.out.println("erster Test");f.delete();kelondroFixedWidthArray k = new kelondroFixedWidthArray(f, rowdef, 6);- k.overwrite(3, k.row().newEntry(new byte[][]{+ k.set(3, k.row().newEntry(new byte[][]{"test123".getBytes(), "abcd".getBytes()}));k.add(k.row().newEntry(new byte[][]{"test456".getBytes(), "efgh".getBytes()}));diff --git a/source/de/anomic/kelondro/kelondroFlexSplitTable.java b/source/de/anomic/kelondro/kelondroFlexSplitTable.javaindex 070ed45cb..e73d54f6f 100644--- a/source/de/anomic/kelondro/kelondroFlexSplitTable.java+++ b/source/de/anomic/kelondro/kelondroFlexSplitTable.java@@ -95,10 +95,10 @@ public class kelondroFlexSplitTable implements kelondroIndex {// open next biggest tablet.remove(maxf);date = maxf.substring(tablename.length() + 1);- if (buffersize >= maxram) {+ if (buffersize >= maxram * 2) {// this will cause usage of a complete RAM index- table = new kelondroCache(new kelondroFlexTable(path, maxf, maxram, preloadTime, rowdef), maxram / 10, true, false);- buffersize -= maxram;+ table = new kelondroCache(new kelondroFlexTable(path, maxf, maxram * 2, preloadTime, rowdef), maxram / 10, true, false);+ buffersize -= maxram * 2;buffersize -= maxram / 10;} else {// this will cause a generation of a file indexdiff --git a/source/de/anomic/kelondro/kelondroFlexTable.java b/source/de/anomic/kelondro/kelondroFlexTable.javaindex 44cf55bb9..b6e4e423a 100644--- a/source/de/anomic/kelondro/kelondroFlexTable.java+++ b/source/de/anomic/kelondro/kelondroFlexTable.java@@ -110,7 +110,7 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondrpublic boolean has(byte[] key) throws IOException {// it is not recommended to implement or use a has predicate unless// it can be ensured that it causes no IO- assert (RAMIndex == true);+ assert (RAMIndex == true) : "RAM index warning in file " + super.tablename;return index.geti(key) >= 0;}@@ -193,7 +193,9 @@ public class kelondroFlexTable extends kelondroFlexWidthArray implements kelondrindex.puti(row.getColBytes(0), super.add(row));return null;}- return super.replace(i, row);+ kelondroRow.Entry oldentry = super.get(i);+ super.set(i, row);+ return oldentry;}public synchronized void addUnique(kelondroRow.Entry row, Date entryDate) throws IOException {diff --git a/source/de/anomic/kelondro/kelondroFlexWidthArray.java b/source/de/anomic/kelondro/kelondroFlexWidthArray.javaindex ca90bb2c7..1cf8a7143 100644--- a/source/de/anomic/kelondro/kelondroFlexWidthArray.java+++ b/source/de/anomic/kelondro/kelondroFlexWidthArray.java@@ -154,7 +154,13 @@ public class kelondroFlexWidthArray implements kelondroArray {public void close() throws IOException {synchronized (col) {- for (int i = 0; i < col.length; i++) if (col[i] != null) col[i].close();+ for (int i = 0; i < col.length; i++) {+ if (col[i] != null) {+ // a column can be null, this is normal+ col[i].close();+ col[i] = null;+ }+ }}}@@ -176,30 +182,7 @@ public class kelondroFlexWidthArray implements kelondroArray {return col[0].size();}- public kelondroRow.Entry replace(int index, kelondroRow.Entry rowentry) throws IOException {- assert rowentry.bytes().length == this.rowdef.objectsize;- int c = 0;- kelondroRow.Entry e0, e1, p;- p = rowdef.newEntry();- int lastcol;- synchronized (col) {- while (c < rowdef.columns()) {- lastcol = c + col[c].row().columns() - 1;- e0 = col[c].row().newEntry(- rowentry.bytes(),- rowdef.colstart[c],- rowdef.colstart[lastcol] - rowdef.colstart[c] + rowdef.width(lastcol));- e1 = col[c].replace(index, e0);- for (int i = 0; i < col[c].row().columns(); i++) {- p.setCol(c + i, e1.getColBytes(i));- }- c = c + col[c].row().columns();- }- }- return p;- }-- public void overwrite(int index, kelondroRow.Entry rowentry) throws IOException {+ public void set(int index, kelondroRow.Entry rowentry) throws IOException {assert rowentry.bytes().length == this.rowdef.objectsize;int c = 0;kelondroRow.Entry e0;@@ -211,7 +194,7 @@ public class kelondroFlexWidthArray implements kelondroArray {rowentry.bytes(),rowdef.colstart[c],rowdef.colstart[lastcol] - rowdef.colstart[c] + rowdef.width(lastcol));- col[c].overwrite(index, e0);+ col[c].set(index, e0);c = c + col[c].row().columns();}}@@ -233,7 +216,7 @@ public class kelondroFlexWidthArray implements kelondroArray {rowentry.bytes(),rowdef.colstart[c],rowdef.colstart[lastcol] + rowdef.width(lastcol) - rowdef.colstart[c]);- col[c].overwrite(index,e);+ col[c].set(index,e);c = c + col[c].row().columns();}}@@ -265,7 +248,7 @@ public class kelondroFlexWidthArray implements kelondroArray {// the other columns will be blanked out onlywhile (r < rowdef.columns()) {- col[r].overwrite(index, null);+ col[r].set(index, null);r = r + col[r].row().columns();}}@@ -274,7 +257,7 @@ public class kelondroFlexWidthArray implements kelondroArray {public void print() throws IOException {System.out.println("PRINTOUT of table, length=" + size());kelondroRow.Entry row;- for (int i = 0; i < col[0].USAGE.allCount(); i++) {+ for (int i = 0; i < (col[0].free() + col[0].size()); i++) {System.out.print("row " + i + ": ");row = get(i);System.out.println(row.toString());diff --git a/source/de/anomic/kelondro/kelondroHashtable.java b/source/de/anomic/kelondro/kelondroHashtable.javaindex 2bcff10c0..c8680935a 100644--- a/source/de/anomic/kelondro/kelondroHashtable.java+++ b/source/de/anomic/kelondro/kelondroHashtable.java@@ -208,13 +208,13 @@ public class kelondroHashtable {}// make space- while (rowNumber >= hashArray.size()) hashArray.overwrite(hashArray.size(), dummyRow);+ while (rowNumber >= hashArray.size()) hashArray.set(hashArray.size(), dummyRow);// write rowkelondroRow.Entry newhkrow = hashArray.row().newEntry();newhkrow.setCol(0, hash.key());newhkrow.setCol(1, rowentry.bytes());- hashArray.overwrite(rowNumber, newhkrow);+ hashArray.set(rowNumber, newhkrow);return hashArray.row().newEntry(oldhkrow.getColBytes(1));}diff --git a/source/de/anomic/kelondro/kelondroRecords.java b/source/de/anomic/kelondro/kelondroRecords.javaindex 275918034..66ce49de9 100644--- a/source/de/anomic/kelondro/kelondroRecords.java+++ b/source/de/anomic/kelondro/kelondroRecords.java@@ -77,6 +77,7 @@ import java.util.Random;import java.util.Set;import java.util.StringTokenizer;import java.util.TreeSet;+import java.util.logging.Level;import java.util.logging.Logger;import de.anomic.server.serverMemory;@@ -85,69 +86,70 @@ import de.anomic.server.logging.serverLog;public class kelondroRecords {// constants- private static final int NUL = Integer.MIN_VALUE; // the meta value for the kelondroRecords' NUL abstraction- private static final long memBlock = 500000; // do not fill cache further if the amount of available memory is less that this- public final static boolean useWriteBuffer = false;+ protected final static int NUL = Integer.MIN_VALUE; // the meta value for the kelondroRecords' NUL abstraction+ private final static long memBlock = 500000; // do not fill cache further if the amount of available memory is less that this+ public final static boolean useWriteBuffer = false; // currently only used during development/testing// memory calculation- private static final int element_in_cache = 4; // for kelondroCollectionObjectMap: 4; for HashMap: 52+ private static final int element_in_cache = 4; // for kelondroCollectionObjectMap: 4; for HashMap: 52// caching flags- public static final int CP_NONE = -1; // cache priority none; entry shall not be cached- public static final int CP_LOW = 0; // cache priority low; entry may be cached- public static final int CP_MEDIUM = 1; // cache priority medium; entry shall be cached- public static final int CP_HIGH = 2; // cache priority high; entry must be cached+ public static final int CP_NONE = -1; // cache priority none; entry shall not be cached+ public static final int CP_LOW = 0; // cache priority low; entry may be cached+ public static final int CP_MEDIUM = 1; // cache priority medium; entry shall be cached+ public static final int CP_HIGH = 2; // cache priority high; entry must be cached// static seek pointers- public static int LEN_DESCR = 60;- protected static long POS_MAGIC = 0; // 1 byte, byte: file type magic- protected static long POS_BUSY = POS_MAGIC + 1; // 1 byte, byte: marker for synchronization- protected static long POS_PORT = POS_BUSY + 1; // 2 bytes, short: hint for remote db access- protected static long POS_DESCR = POS_PORT + 2; // 60 bytes, string: any description string- protected static long POS_COLUMNS = POS_DESCR + LEN_DESCR; // 2 bytes, short: number of columns in one entry- protected static long POS_OHBYTEC = POS_COLUMNS + 2; // 2 bytes, number of extra bytes on each Node- protected static long POS_OHHANDLEC = POS_OHBYTEC + 2; // 2 bytes, number of Handles on each Node- protected static long POS_USEDC = POS_OHHANDLEC + 2; // 4 bytes, int: used counter- protected static long POS_FREEC = POS_USEDC + 4; // 4 bytes, int: free counter- protected static long POS_FREEH = POS_FREEC + 4; // 4 bytes, int: free pointer (to free chain start)- protected static long POS_MD5PW = POS_FREEH + 4; // 16 bytes, string (encrypted password to this file)- protected static long POS_ENCRYPTION = POS_MD5PW + 16; // 16 bytes, string (method description)- protected static long POS_OFFSET = POS_ENCRYPTION + 16; // 8 bytes, long (seek position of first record)- protected static long POS_INTPROPC = POS_OFFSET + 8; // 4 bytes, int: number of INTPROP elements- protected static long POS_TXTPROPC = POS_INTPROPC + 4; // 4 bytes, int: number of TXTPROP elements- protected static long POS_TXTPROPW = POS_TXTPROPC + 4; // 4 bytes, int: width of TXTPROP elements- protected static long POS_COLWIDTHS = POS_TXTPROPW + 4; // array of 4 bytes, int[]: sizes of columns+ private static int LEN_DESCR = 60;+ private static long POS_MAGIC = 0; // 1 byte, byte: file type magic+ private static long POS_BUSY = POS_MAGIC + 1; // 1 byte, byte: marker for synchronization+ private static long POS_PORT = POS_BUSY + 1; // 2 bytes, short: hint for remote db access+ private static long POS_DESCR = POS_PORT + 2; // 60 bytes, string: any description string+ private static long POS_COLUMNS = POS_DESCR + LEN_DESCR; // 2 bytes, short: number of columns in one entry+ private static long POS_OHBYTEC = POS_COLUMNS + 2; // 2 bytes, number of extra bytes on each Node+ private static long POS_OHHANDLEC = POS_OHBYTEC + 2; // 2 bytes, number of Handles on each Node+ private static long POS_USEDC = POS_OHHANDLEC + 2; // 4 bytes, int: used counter+ private static long POS_FREEC = POS_USEDC + 4; // 4 bytes, int: free counter+ private static long POS_FREEH = POS_FREEC + 4; // 4 bytes, int: free pointer (to free chain start)+ private static long POS_MD5PW = POS_FREEH + 4; // 16 bytes, string (encrypted password to this file)+ private static long POS_ENCRYPTION = POS_MD5PW + 16; // 16 bytes, string (method description)+ private static long POS_OFFSET = POS_ENCRYPTION + 16; // 8 bytes, long (seek position of first record)+ private static long POS_INTPROPC = POS_OFFSET + 8; // 4 bytes, int: number of INTPROP elements+ private static long POS_TXTPROPC = POS_INTPROPC + 4; // 4 bytes, int: number of TXTPROP elements+ private static long POS_TXTPROPW = POS_TXTPROPC + 4; // 4 bytes, int: width of TXTPROP elements+ private static long POS_COLWIDTHS = POS_TXTPROPW + 4; // array of 4 bytes, int[]: sizes of columns// after this configuration field comes:// POS_HANDLES: INTPROPC * 4 bytes : INTPROPC Integer properties, randomly accessible// POS_TXTPROPS: TXTPROPC * TXTPROPW : an array of TXTPROPC byte arrays of width TXTPROPW that can hold any string// POS_NODES : (USEDC + FREEC) * (overhead + sum(all: COLWIDTHS)) : Node Objects// values that are only present at run-time- protected String filename; // the database's file name- protected kelondroIOChunks entryFile; // the database file- protected int overhead; // OHBYTEC + 4 * OHHANDLEC = size of additional control bytes- protected int headchunksize;// overheadsize + key element column size- protected int tailchunksize;// sum(all: COLWIDTHS) minus the size of the key element colum- protected int recordsize; // (overhead + sum(all: COLWIDTHS)) = the overall size of a record+ protected String filename; // the database's file name+ private kelondroIOChunks entryFile; // the database file+ private int overhead; // OHBYTEC + 4 * OHHANDLEC = size of additional control bytes+ private int headchunksize;// overheadsize + key element column size+ private int tailchunksize;// sum(all: COLWIDTHS) minus the size of the key element colum+ private int recordsize; // (overhead + sum(all: COLWIDTHS)) = the overall size of a record+ private byte[] spaceChunk; // a chunk of data that is used to reserve space within the file// dynamic run-time seek pointers- protected long POS_HANDLES = 0; // starts after end of POS_COLWIDHS which is POS_COLWIDTHS + COLWIDTHS.length * 4- protected long POS_TXTPROPS = 0; // starts after end of POS_HANDLES which is POS_HANDLES + HANDLES.length * 4- protected long POS_NODES = 0; // starts after end of POS_TXTPROPS which is POS_TXTPROPS + TXTPROPS.length * TXTPROPW+ private long POS_HANDLES = 0; // starts after end of POS_COLWIDHS which is POS_COLWIDTHS + COLWIDTHS.length * 4+ private long POS_TXTPROPS = 0; // starts after end of POS_HANDLES which is POS_HANDLES + HANDLES.length * 4+ private long POS_NODES = 0; // starts after end of POS_TXTPROPS which is POS_TXTPROPS + TXTPROPS.length * TXTPROPW// dynamic variables that are back-ups of stored values in file; read/defined on instantiation- protected usageControl USAGE; // counter for used and re-use records and pointer to free-list- protected short OHBYTEC; // number of extra bytes in each node- protected short OHHANDLEC; // number of handles in each node- protected kelondroRow ROW; // array with widths of columns- protected Handle HANDLES[]; // array with handles- protected byte[] TXTPROPS[]; // array with text properties- protected int TXTPROPW; // size of a single TXTPROPS element+ private usageControl USAGE; // counter for used and re-use records and pointer to free-list+ private short OHBYTEC; // number of extra bytes in each node+ private short OHHANDLEC; // number of handles in each node+ private kelondroRow ROW; // array with widths of columns+ private Handle HANDLES[]; // array with handles+ private byte[] TXTPROPS[]; // array with text properties+ private int TXTPROPW; // size of a single TXTPROPS element// caching buffer- protected kelondroIntBytesMap cacheHeaders; // the cache; holds overhead values and key element- protected int cacheSize; // number of cache records- protected int readHit, readMiss, writeUnique, writeDouble, cacheDelete, cacheFlush;+ private kelondroIntBytesMap cacheHeaders; // the cache; holds overhead values and key element+ private int cacheSize; // number of cache records+ private int readHit, readMiss, writeUnique, writeDouble, cacheDelete, cacheFlush;// optional loggerprotected Logger theLogger = Logger.getLogger("KELONDRO"); // default logger@@ -158,41 +160,212 @@ public class kelondroRecords {// Random. This is used to shift flush-times of write-buffers to differrent timeprivate static Random random = new Random(System.currentTimeMillis());+ // check for debug mode+ private static boolean debugmode = false;+ static {+ assert debugmode = true;+ }+protected final class usageControl {- protected int USEDC; // counter of used elements- protected int FREEC; // counter of free elements in list of free Nodes- protected Handle FREEH; // pointer to first element in list of free Nodes, empty = NUL-- public usageControl() throws IOException {- read();+ private int USEDC; // counter of used elements+ private int FREEC; // counter of free elements in list of free Nodes+ private Handle FREEH; // pointer to first element in list of free Nodes, empty = NUL++ public usageControl(boolean init) throws IOException {+ if (init) {+ this.USEDC = 0;+ this.FREEC = 0;+ this.FREEH = new Handle(NUL);+ } else {+ readfree();+ readused();+ try {+ int rest = (int) ((entryFile.length() - POS_NODES) % recordsize);// == 0 : "rest = " + ((entryFile.length() - POS_NODES) % ((long) recordsize)) + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;+ int calculated_used = (int) ((entryFile.length() - POS_NODES) / recordsize);+ if ((rest != 0) || (calculated_used != this.USEDC + this.FREEC)) {+ theLogger.log(Level.WARNING, "USEDC inconsistency at startup: calculated_used = " + calculated_used + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename);+ this.USEDC = calculated_used - this.FREEC;+ writeused(true);+ }+ } catch (IOException e) {+ assert false;+ }+ }}- public usageControl(int usedc, int freec, Handle freeh) {- this.USEDC = usedc;- this.FREEC = freec;- this.FREEH = freeh;+ private synchronized void writeused(boolean finalwrite) throws IOException {+ // we write only at close time, not in between. othervise, the read/write head+ // needs to run up and own all the way between the beginning and the end of the+ // file for each record. We check consistency beteen file size and+ if (finalwrite) synchronized (entryFile) {+ entryFile.writeInt(POS_USEDC, USEDC);+ entryFile.commit();+ }}- public void write() throws IOException {+ private synchronized void writefree() throws IOException {synchronized (entryFile) {- entryFile.writeInt(POS_USEDC, USEDC);entryFile.writeInt(POS_FREEC, FREEC);entryFile.writeInt(POS_FREEH, FREEH.index);entryFile.commit();+ checkConsistency();}}- public void read() throws IOException {+ private synchronized void readused() throws IOException {synchronized (entryFile) {this.USEDC = entryFile.readInt(POS_USEDC);+ }+ }++ private synchronized void readfree() throws IOException {+ synchronized (entryFile) {this.FREEC = entryFile.readInt(POS_FREEC);this.FREEH = new Handle(entryFile.readInt(POS_FREEH));}}- public int allCount() {+ private synchronized int allCount() {+ checkConsistency();return this.USEDC + this.FREEC;}++ private synchronized int used() {+ checkConsistency();+ return this.USEDC;+ }++ private synchronized void dispose(Handle h) throws IOException {+ // delete element with handle h+ // this element is then connected to the deleted-chain and can be+ // re-used change counter+ assert (h.index >= 0);+ assert (h.index != NUL);+ assert (h.index < USEDC + FREEC) : "USEDC = " + USEDC + ", FREEC = " + FREEC + ", h.index = " + h.index;+ long sp = seekpos(h);+ assert (sp <= entryFile.length() + ROW.objectsize) : h.index + "/" + sp + " exceeds file size " + entryFile.length();+ synchronized (USAGE) {+ USEDC--;+ FREEC++;+ // change pointer+ entryFile.writeInt(sp, FREEH.index); // extend free-list+ // write new FREEH Handle link+ FREEH = h;+ writefree();+ writeused(false);+ }+ }++ private synchronized int allocate(byte[] chunk) throws IOException {+ // reserves a new record and returns index of record+ // the return value is not a seek position+ // the seek position can be retrieved using the seekpos() function+ if (chunk == null) {+ chunk = spaceChunk;+ }+ assert (chunk.length == ROW.objectsize()) : "chunk.length = " + chunk.length + ", ROW.objectsize() = " + ROW.objectsize();+ synchronized (USAGE) {+ if (USAGE.FREEC == 0) {+ // generate new entry+ int index = USAGE.allCount();+ entryFile.write(seekpos(index) + overhead, chunk, 0, ROW.objectsize()); // occupy space, othervise the USAGE computaton does not work+ USAGE.USEDC++;+ writeused(false);+ return index;+ } else {+ // re-use record from free-list+ USAGE.USEDC++;+ USAGE.FREEC--;+ // take link+ int index;+ if (USAGE.FREEH.index == NUL) {+ serverLog.logSevere("kelondroRecords/" + filename, "INTERNAL ERROR (DATA INCONSISTENCY): re-use of records failed, lost " + (USAGE.FREEC + 1) + " records.");+ // try to heal..+ USAGE.USEDC = USAGE.allCount() + 1;+ USAGE.FREEC = 0;+ index = USAGE.USEDC - 1;+ } else {+ index = USAGE.FREEH.index;+ //System.out.println("*DEBUG* ALLOCATED DELETED INDEX " + index);+ // check for valid seek position+ long seekp = seekpos(USAGE.FREEH);+ if (seekp > entryFile.length()) {+ // this is a severe inconsistency. try to heal..+ serverLog.logSevere("kelondroRecords/" + filename, "new Handle: lost " + USAGE.FREEC + " marked nodes; seek position " + seekp + "/" + USAGE.FREEH.index + " out of file size " + entryFile.length() + "/" + ((entryFile.length() - POS_NODES) / recordsize));+ index = USAGE.allCount(); // a place at the end of the file+ USAGE.USEDC += USAGE.FREEC; // to avoid that non-empty records at the end are overwritten+ USAGE.FREEC = 0; // discard all possible empty nodes+ USAGE.FREEH.index = NUL;+ } else {+ // read link to next element of FREEH chain+ USAGE.FREEH.index = entryFile.readInt(seekp);+ }+ }+ USAGE.writeused(false);+ USAGE.writefree();+ entryFile.write(seekpos(index) + overhead, chunk, 0, ROW.objectsize()); // overwrite space+ return index;+ }+ }+ }++ private synchronized void allocate(int index, byte[] chunk, int offset, boolean write) throws IOException {+ // in case that the handle index was created outside this class,+ // this method ensures that the USAGE counters are consistent with the+ // new handle index+ if (chunk == null) {+ chunk = new byte[ROW.objectsize()];+ offset = 0;+ }+ //assert (chunk.length == ROW.objectsize()) : "chunk.length = " + chunk.length + ", ROW.objectsize() = " + ROW.objectsize();+ synchronized (USAGE) {+ if (index < USAGE.allCount()) {+ // write within the file+ // this can be critical, if we simply overwrite fields that are marked+ // as deleted. This case should be avoided. There is no other way to check+ // that the field is not occupied than looking at the FREEC counter+ assert (USAGE.FREEC == 0) : "FREEC = " + USAGE.FREEC;+ // simply overwrite the cell+ if (write) entryFile.write(seekpos(index) + overhead, chunk, offset, ROW.objectsize());+ // no changes of counter necessary+ } else {+ assert write == true;+ // write beyond the end of the file+ // records that are in between are marked as deleted+ Handle h;+ while (index > USAGE.allCount()) {+ h = new Handle(USAGE.allCount());+ USAGE.FREEC++;+ entryFile.write(seekpos(h), spaceChunk); // occupy space, othervise the USAGE computaton does not work+ entryFile.writeInt(seekpos(h), USAGE.FREEH.index);+ USAGE.FREEH = h;+ USAGE.writefree();+ entryFile.commit();+ }+ assert (index <= USAGE.allCount());++ // adopt USAGE.USEDC+ if (USAGE.allCount() == index) {+ entryFile.write(seekpos(index) + overhead, chunk, offset, ROW.objectsize()); // write chunk and occupy space+ USAGE.USEDC++;+ USAGE.writeused(false);+ entryFile.commit();+ }+ }+ }+ }+++ private synchronized void checkConsistency() {+ if (debugmode) try { // in debug mode+ long efl = entryFile.length();+ assert ((efl - POS_NODES) % ((long) recordsize)) == 0 : "rest = " + ((entryFile.length() - POS_NODES) % ((long) recordsize)) + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;+ long calculated_used = (efl - POS_NODES) / ((long) recordsize);+ assert calculated_used == this.USEDC + this.FREEC : "calculated_used = " + calculated_used + ", USEDC = " + this.USEDC + ", FREEC = " + this.FREEC + ", recordsize = " + recordsize + ", file = " + filename;+ } catch (IOException e) {+ assert false;+ }+ }}public static int staticsize(File file) {@@ -201,10 +374,10 @@ public class kelondroRecords {kelondroRA ra = new kelondroFileRA(file.getCanonicalPath());kelondroIOChunks entryFile = new kelondroRAIOChunks(ra, ra.name());- int USEDC = entryFile.readInt(POS_USEDC);+ int used = entryFile.readInt(POS_USEDC); // works only if consistency with file size is givenentryFile.close();ra.close();- return USEDC;+ return used;} catch (FileNotFoundException e) {return 0;} catch (IOException e) {@@ -251,7 +424,6 @@ public class kelondroRecords {writeOrderType();}initCache(buffersize / 10 * 9, preloadTime);-}public kelondroRecords(kelondroRA ra, long buffersize /* bytes */, long preloadTime,@@ -290,14 +462,16 @@ public class kelondroRecords {this.recordsize = this.overhead + ROW.objectsize();this.headchunksize = overhead + ROW.width(0);this.tailchunksize = this.recordsize - this.headchunksize;+ this.spaceChunk = fillSpaceChunk(recordsize);// store dynamic run-time seek pointersPOS_HANDLES = POS_COLWIDTHS + ROW.columns() * 4;POS_TXTPROPS = POS_HANDLES + FHandles * 4;POS_NODES = POS_TXTPROPS + txtProps * txtPropWidth;+ //System.out.println("*** DEBUG: POS_NODES = " + POS_NODES + " for " + filename);// store dynamic back-up variables- USAGE = new usageControl(0, 0, new Handle(NUL));+ USAGE = new usageControl(true);OHBYTEC = ohbytec;OHHANDLEC = ohhandlec;HANDLES = new Handle[FHandles];@@ -314,8 +488,8 @@ public class kelondroRecords {entryFile.writeShort(POS_COLUMNS, this.ROW.columns());entryFile.writeShort(POS_OHBYTEC, OHBYTEC);entryFile.writeShort(POS_OHHANDLEC, OHHANDLEC);- entryFile.writeInt(POS_USEDC, this.USAGE.USEDC);- entryFile.writeInt(POS_FREEC, this.USAGE.FREEC);+ entryFile.writeInt(POS_USEDC, 0);+ entryFile.writeInt(POS_FREEC, 0);entryFile.writeInt(POS_FREEH, this.USAGE.FREEH.index);entryFile.write(POS_MD5PW, "PASSWORDPASSWORD".getBytes());entryFile.write(POS_ENCRYPTION, "ENCRYPTION!#$%&?".getBytes());@@ -341,6 +515,12 @@ public class kelondroRecords {this.entryFile.commit();}+ private static final byte[] fillSpaceChunk(int size) {+ byte[] chunk = new byte[size];+ while (--size >= 0) chunk[size] = (byte) 0xff;+ return chunk;+ }+public void setDescription(byte[] description) throws IOException {if (description.length > LEN_DESCR)entryFile.write(POS_DESCR, description, 0, LEN_DESCR);@@ -378,17 +558,6 @@ public class kelondroRecords {elsethis.theLogger.fine("KELONDRO DEBUG " + this.filename + ": " + message);}-- public void clear() throws IOException {- // Removes all mappings from this map- // throw new UnsupportedOperationException("clear not supported");- synchronized (USAGE) {- this.USAGE.USEDC = 0;- this.USAGE.FREEC = 0;- this.USAGE.FREEH = new Handle(NUL);- }- this.USAGE.write();- }public kelondroRecords(kelondroRA ra, long buffersize, long preloadTime) throws IOException{this.fileExisted = false;@@ -408,8 +577,7 @@ public class kelondroRecords {// read dynamic variables that are back-ups of stored values in file;// read/defined on instantiation- this.USAGE = new usageControl();-+this.OHBYTEC = entryFile.readShort(POS_OHBYTEC);this.OHHANDLEC = entryFile.readShort(POS_OHHANDLEC);@@ -424,6 +592,7 @@ public class kelondroRecords {POS_HANDLES = POS_COLWIDTHS + COLDEFS.length * 4;POS_TXTPROPS = POS_HANDLES + HANDLES.length * 4;POS_NODES = POS_TXTPROPS + TXTPROPS.length * TXTPROPW;+ //System.out.println("*** DEBUG: POS_NODES = " + POS_NODES + " for " + filename);// read configuration arraysfor (int i = 0; i < COLDEFS.length; i++) {@@ -440,10 +609,13 @@ public class kelondroRecords {// assign remaining values that are only present at run-timethis.overhead = OHBYTEC + 4 * OHHANDLEC;- this.recordsize = this.overhead;this.recordsize = this.overhead + ROW.objectsize();this.headchunksize = this.overhead + this.ROW.width(0);this.tailchunksize = this.recordsize - this.headchunksize;+ this.spaceChunk = fillSpaceChunk(recordsize);++ // init USAGE, must be done at the end because it needs the recordsize value+ this.USAGE = new usageControl(false);}private void writeOrderType() {@@ -583,31 +755,29 @@ public class kelondroRecords {return bulk;}- protected final Node newNode() throws IOException {- return new Node();+ protected synchronized final Node newNode(byte[] row) throws IOException {+ return new Node(row);}- protected final Node newNode(Handle handle, byte[] bulkchunk, int offset) {- return new Node(handle, bulkchunk, offset, true);+ protected synchronized final Node newNode(Handle handle, byte[] bulkchunk, int offset, boolean write) throws IOException {+ return new Node(handle, bulkchunk, offset, write);}- protected final Node getNode(Handle handle) throws IOException {- return getNode(handle, null, 0);+ protected synchronized final Node getNode(Handle handle, boolean fillTail) throws IOException {+ return getNode(handle, null, 0, fillTail);}- protected final Node getNode(Handle handle, Node parentNode, int referenceInParent) throws IOException {- return new Node(handle, parentNode, referenceInParent);+ protected synchronized final Node getNode(Handle handle, Node parentNode, int referenceInParent, boolean fillTail) throws IOException {+ return new Node(handle, parentNode, referenceInParent, fillTail);}- protected final void deleteNode(Handle handle) throws IOException {- if (cacheSize == 0) {- dispose(handle);- } else {- synchronized (cacheHeaders) {- cacheHeaders.removeb(handle.index);- cacheDelete++;- dispose(handle);- }+ protected synchronized final void deleteNode(Handle handle) throws IOException {+ if ((cacheHeaders == null) || (cacheSize == 0)) {+ USAGE.dispose(handle);+ } else synchronized (cacheHeaders) {+ cacheHeaders.removeb(handle.index);+ cacheDelete++;+ USAGE.dispose(handle);}}@@ -641,26 +811,53 @@ public class kelondroRecords {protected Handle handle = null; // index of the entry, by default NUL means undefinedprotected byte[] headChunk = null; // contains ohBytes, ohHandles and the key valueprotected byte[] tailChunk = null; // contains all values except the key value- protected boolean headChanged = true;- protected boolean tailChanged = true;-- protected Node() throws IOException {- // create a new empty node and reserve empty space in file for it- // use this method only if you want to extend the file with new entries- // without the need to have content in it.- this.handle = new Handle();+ protected boolean headChanged = false;+ protected boolean tailChanged = false;+ protected Node(byte[] rowinstance) throws IOException {+ // this initializer is used to create nodes from bulk-read byte arrays+ assert ((rowinstance == null) || (rowinstance.length == ROW.objectsize)) : "bulkchunk.length = " + rowinstance.length + ", ROW.width(0) = " + ROW.width(0);+ this.handle = new Handle(USAGE.allocate(rowinstance));+// create empty chunksthis.headChunk = new byte[headchunksize];this.tailChunk = new byte[tailchunksize];- for (int i = headchunksize - 1; i >= 0; i--) this.headChunk[i] = 0;- for (int i = tailchunksize - 1; i >= 0; i--) this.tailChunk[i] = 0;++ // write content to chunks+ if (rowinstance == null) {+ for (int i = headchunksize - 1; i >= 0; i--) this.headChunk[i] = (byte) 0xff;+ for (int i = tailchunksize - 1; i >= 0; i--) this.tailChunk[i] = (byte) 0xff;+ } else {+ for (int i = overhead - 1; i >= 0; i--) this.headChunk[i] = (byte) 0xff;+ System.arraycopy(rowinstance, 0, this.headChunk, overhead, ROW.width(0));+ System.arraycopy(rowinstance, ROW.width(0), this.tailChunk, 0, tailchunksize);+ }++ // mark chunks as changed+ // if the head/tail chunks come from a file system read, setChanged should be false+ // if the chunks come from a overwrite attempt, it should be true+ this.headChanged = false; // we wrote the head already during allocate+ this.tailChanged = false; // we write the tail already during allocate++ // update cache+ update2Cache(CP_LOW);}-- protected Node(Handle handle, byte[] bulkchunk, int offset, boolean setChanged) {++ protected Node(Handle handle, byte[] bulkchunk, int offset, boolean write) throws IOException {// this initializer is used to create nodes from bulk-read byte arrays+ // if write is true, then the chunk in bulkchunk is written to the file+ // othervise it is considered equal to what is stored in the file+ // (that is ensured during pre-loaded enumeration)this.handle = handle;- assert ((bulkchunk == null) || (bulkchunk.length >= offset + headchunksize)) : "bulkchunk.length = " + bulkchunk.length + ", offset = " + offset + ", headchunksize = " + headchunksize;+ boolean changed;+ if (handle.index >= USAGE.allCount()) {+ assert write == true : "handle.index = " + handle.index + ", USAGE.allCount() = " + USAGE.allCount();+ USAGE.allocate(handle.index, bulkchunk, offset, write);+ changed = false; // this is independent from write+ } else {+ changed = write;+ }+ assert ((bulkchunk == null) || (bulkchunk.length >= offset + ROW.width(0))) : "bulkchunk.length = " + bulkchunk.length + ", offset = " + offset + ", ROW.width(0) = " + ROW.width(0);// create empty chunksthis.headChunk = new byte[headchunksize];@@ -668,18 +865,18 @@ public class kelondroRecords {// write content to chunksif (bulkchunk != null) {- System.arraycopy(bulkchunk, offset, this.headChunk, 0, headchunksize);- System.arraycopy(bulkchunk, offset + headchunksize, this.tailChunk, 0, tailchunksize);+ System.arraycopy(bulkchunk, offset, this.headChunk, overhead, ROW.width(0));+ System.arraycopy(bulkchunk, offset + ROW.width(0), this.tailChunk, 0, tailchunksize);}// mark chunks as changed// if the head/tail chunks come from a file system read, setChanged should be false// if the chunks come from a overwrite attempt, it should be true- this.headChanged = setChanged;- this.tailChanged = setChanged;+ this.headChanged = changed;+ this.tailChanged = changed;}- protected Node(Handle handle, Node parentNode, int referenceInParent) throws IOException {+ protected Node(Handle handle, Node parentNode, int referenceInParent, boolean fillTail) throws IOException {// this creates an entry with an pre-reserved entry position.// values can be written using the setValues() method,// but we expect that values are already there in the file.@@ -703,18 +900,28 @@ public class kelondroRecords {// use given handlethis.handle = new Handle(handle.index);+ // check for memory availability when fillTail is requested+ if ((fillTail) && (tailchunksize > 10000)) fillTail = false; // this is a fail-safe 'short version' of a memory check+// init the content- initContent();- }-- private void initContent() throws IOException {// create chunks; read them from file or cachethis.tailChunk = null;if (cacheSize == 0) {- // read overhead and key- //System.out.println("**NO CACHE for " + this.handle.index + "**");- this.headChunk = new byte[headchunksize];- entryFile.readFully(seekpos(this.handle), this.headChunk, 0, this.headChunk.length);+ if (fillTail) {+ // read complete record+ byte[] chunkbuffer = new byte[recordsize];+ entryFile.readFully(seekpos(this.handle), chunkbuffer, 0, recordsize);+ this.headChunk = new byte[headchunksize];+ this.tailChunk = new byte[tailchunksize];+ System.arraycopy(chunkbuffer, 0, this.headChunk, 0, headchunksize);+ System.arraycopy(chunkbuffer, headchunksize, this.tailChunk, 0, tailchunksize);+ chunkbuffer = null;+ } else {+ // read overhead and key+ this.headChunk = new byte[headchunksize];+ this.tailChunk = null;+ entryFile.readFully(seekpos(this.handle), this.headChunk, 0, headchunksize);+ }} else synchronized(cacheHeaders) {byte[] cacheEntry = null;int cp = CP_HIGH;@@ -722,11 +929,22 @@ public class kelondroRecords {if (cacheEntry == null) {// cache miss, we read overhead and key from filereadMiss++;- //System.out.println("**CACHE miss for " + this.handle.index + "**");- this.headChunk = new byte[headchunksize];- //this.tailChunk = new byte[tailchunksize];- entryFile.readFully(seekpos(this.handle), this.headChunk, 0, this.headChunk.length);-+ if (fillTail) {+ // read complete record+ byte[] chunkbuffer = new byte[recordsize];+ entryFile.readFully(seekpos(this.handle), chunkbuffer, 0, recordsize);+ this.headChunk = new byte[headchunksize];+ this.tailChunk = new byte[tailchunksize];+ System.arraycopy(chunkbuffer, 0, this.headChunk, 0, headchunksize);+ System.arraycopy(chunkbuffer, headchunksize, this.tailChunk, 0, tailchunksize);+ chunkbuffer = null;+ } else {+ // read overhead and key+ this.headChunk = new byte[headchunksize];+ this.tailChunk = null;+ entryFile.readFully(seekpos(this.handle), this.headChunk, 0, headchunksize);+ }+// calculate cache prioritycp = CP_HIGH;if (OHHANDLEC == 3) {@@ -739,14 +957,7 @@ public class kelondroRecords {// if space left in cache, copy these value to the cacheupdate2Cache(cp);} else {- //System.out.print("CACHE HIT FOR INDEX " + this.handle.index + ": ");- //for (int i = 0; i < cacheEntry.length; i++) System.out.print(cacheEntry[i] + ", ");- //System.out.println();- // cache hit, copy overhead and key from cachereadHit++;- //System.out.println("**CACHE HIT for " + this.handle.index + "**");- //this.headChunk = new byte[headchunksize];- //System.arraycopy(cacheEntry, 0, this.headChunk, 0, headchunksize);this.headChunk = cacheEntry;}}@@ -768,7 +979,7 @@ public class kelondroRecords {protected Handle handle() {// if this entry has an index, return itif (this.handle.index == NUL) throw new kelondroException(filename, "the entry has no index assigned");- return new Handle(this.handle.index);+ return this.handle;}protected void setOHByte(int i, byte b) {@@ -811,7 +1022,7 @@ public class kelondroRecords {// set valuesif (this.handle.index != NUL) {setValue(row, 0, ROW.width(0), headChunk, overhead);- if (ROW.columns() > 1) setValue(row, ROW.width(0), ROW.objectsize() - ROW.width(0), tailChunk, 0);+ if (ROW.columns() > 1) setValue(row, ROW.width(0), tailchunksize, tailChunk, 0);}this.headChanged = true;this.tailChanged = true;@@ -858,7 +1069,7 @@ public class kelondroRecords {// save headif (this.headChanged) {//System.out.println("WRITEH(" + filename + ", " + seekpos(this.handle) + ", " + this.headChunk.length + ")");- entryFile.write(seekpos(this.handle), this.headChunk);+ entryFile.write(seekpos(this.handle), (this.headChunk == null) ? new byte[headchunksize] : this.headChunk);update2Cache(cachePriority);this.headChanged = false;}@@ -866,7 +1077,7 @@ public class kelondroRecords {// save tailif ((this.tailChunk != null) && (this.tailChanged)) {//System.out.println("WRITET(" + filename + ", " + (seekpos(this.handle) + headchunksize) + ", " + this.tailChunk.length + ")");- entryFile.write(seekpos(this.handle) + headchunksize, this.tailChunk);+ entryFile.write(seekpos(this.handle) + headchunksize, (this.tailChunk == null) ? new byte[tailchunksize] : this.tailChunk);this.tailChanged = false;}@@ -933,6 +1144,7 @@ public class kelondroRecords {if (this.headChunk == null) return; // nothing there to cacheif (priority == CP_NONE) return; // it is not wanted that this shall be cachedif (cacheSize == 0) return; // we do not use the cache+ if (cacheHeaders == null) return; // no cacheif (cacheHeaders.size() >= cacheSize) return; // no cache update if cache is fullsynchronized (cacheHeaders) {@@ -1024,9 +1236,13 @@ public class kelondroRecords {protected final long seekpos(Handle handle) {assert (handle.index >= 0): "handle index too low: " + handle.index;- //assert (handle.index < USAGE.allCount()): "handle index too high:" + handle.index;return POS_NODES + ((long) recordsize * handle.index);}++ protected final long seekpos(int index) {+ assert (index >= 0): "handle index too low: " + index;+ return POS_NODES + ((long) recordsize * index);+ }// additional propertiespublic final synchronized int handles() {@@ -1061,39 +1277,17 @@ public class kelondroRecords {// Returns true if this map contains no key-value mappings.public final boolean isEmpty() {- return (USAGE.USEDC == 0);+ return (USAGE.used() == 0);}// Returns the number of key-value mappings in this map.- public final int size() {- return USAGE.USEDC;+ public int size() {+ return USAGE.used();}protected final int free() {return USAGE.FREEC;}-- private synchronized final void dispose(Handle h) throws IOException {- // delete element with handle h- // this element is then connected to the deleted-chain and can be- // re-used change counter- assert (h.index >= 0);- assert (h.index != NUL);- long sp = seekpos(h);- if (sp >= entryFile.length()) {- // a deletion of a node that cannot exist is wrong- throw new IOException("dispose: handle position " + h.index + "/" + sp + " exceeds file size " + entryFile.length());- }- synchronized (USAGE) {- USAGE.USEDC--;- USAGE.FREEC++;- // change pointer- entryFile.writeInt(sp, USAGE.FREEH.index); // extend free-list- // write new FREEH Handle link- USAGE.FREEH = h;- USAGE.write();- }- }public final Iterator contentRows(long maxInitTime) throws kelondroException {return new contentRowIterator(maxInitTime);@@ -1247,7 +1441,7 @@ public class kelondroRecords {((key.length > 0) && (key[0] == 0)) // a 'lost' pointer within a deleted-chain) {// this is a deleted node; probably not commited with dispose- if (fullyMarked) try {dispose(nn.handle);} catch (IOException e) {} // mark this now as deleted+ if (fullyMarked) try {USAGE.dispose(nn.handle);} catch (IOException e) {} // mark this now as deletedcontinue;}return nn;@@ -1264,7 +1458,7 @@ public class kelondroRecords {}// read node from bulk- Node n = new Node(new Handle(pos.index), bulk, (pos.index - bulkstart) * recordsize, false);+ Node n = new Node(new Handle(pos.index), bulk, (pos.index - bulkstart) * recordsize, true);pos.index++;while ((markedDeleted.contains(pos)) && (pos.index < USAGE.allCount())) pos.index++;return n;@@ -1277,14 +1471,19 @@ public class kelondroRecords {}public void close() throws IOException {- if (this.entryFile != null) this.entryFile.close();- this.entryFile = null;+ if (entryFile == null) {+ theLogger.severe("File was closed before close was called. File = " + filename);+ } else {+ USAGE.writeused(true);+ this.entryFile.close();+ }}public void finalize() {try {- close();+ if (entryFile != null) close();} catch (IOException e) { }+ this.entryFile = null;}protected final static String[] line2args(String line) {@@ -1354,7 +1553,7 @@ public class kelondroRecords {System.out.print(", '" + (new String(TXTPROPS[i])).trim() + "'");System.out.println("}");}- System.out.println(" USEDC : " + USAGE.USEDC);+ System.out.println(" USEDC : " + USAGE.used());System.out.println(" FREEC : " + USAGE.FREEC);System.out.println(" FREEH : " + USAGE.FREEH.toString());System.out.println(" NUL repres.: 0x" + Integer.toHexString(NUL));@@ -1384,7 +1583,7 @@ public class kelondroRecords {System.out.println("--");System.out.println("NODES");for (int i = 0; i < USAGE.allCount(); i++)- System.out.println("NODE: " + new Node(new Handle(i), (Node) null, 0).toString());+ System.out.println("NODE: " + new Node(new Handle(i), (Node) null, 0, true).toString());}public String toString() {@@ -1394,84 +1593,11 @@ public class kelondroRecords {protected final class Handle implements Comparable {protected int index;- protected Handle() throws IOException {- // reserves a new record and returns index of record- // the return value is not a seek position- // the seek position can be retrieved using the seekpos() function- synchronized (USAGE) {- if (USAGE.FREEC == 0) {- // generate new entry- index = USAGE.allCount();- USAGE.USEDC++;- entryFile.writeInt(POS_USEDC, USAGE.USEDC);- entryFile.commit();- } else {- // re-use record from free-list- USAGE.USEDC++;- USAGE.FREEC--;- // take link- if (USAGE.FREEH.index == NUL) {- serverLog.logSevere("kelondroRecords/" + filename, "INTERNAL ERROR (DATA INCONSISTENCY): re-use of records failed, lost " + (USAGE.FREEC + 1) + " records.");- // try to heal..- USAGE.USEDC = USAGE.allCount() + 1;- USAGE.FREEC = 0;- index = USAGE.USEDC - 1;- } else {- index = USAGE.FREEH.index;- //System.out.println("*DEBUG* ALLOCATED DELETED INDEX " + index);- // check for valid seek position- long seekp = seekpos(USAGE.FREEH);- if (seekp > entryFile.length()) {- // this is a severe inconsistency. try to heal..- serverLog.logSevere("kelondroRecords/" + filename, "new Handle: lost " + USAGE.FREEC + " marked nodes; seek position " + seekp + "/" + USAGE.FREEH.index + " out of file size " + entryFile.length() + "/" + ((entryFile.length() - POS_NODES) / recordsize));- index = USAGE.allCount(); // a place at the end of the file- USAGE.USEDC += USAGE.FREEC; // to avoid that non-empty records at the end are overwritten- USAGE.FREEC = 0; // discard all possible empty nodes- USAGE.FREEH.index = NUL;- } else {- // read link to next element of FREEH chain- USAGE.FREEH.index = entryFile.readInt(seekp);- }- }- USAGE.write();- }- }- }-protected Handle(int i) {assert (i == NUL) || (i >= 0) : "node handle index too low: " + i;//assert (i == NUL) || (i < USAGE.allCount()) : "node handle index too high: " + i + ", USEDC=" + USAGE.USEDC + ", FREEC=" + USAGE.FREEC;this.index = i;- }-- protected void adoptAllCount() throws IOException {- // in case that the handle index was created outside this class,- // this method ensures that the USAGE counters are consistent with the- // new handle index- if (USAGE.allCount() <= this.index) synchronized (USAGE) {- // records that are in between are marked as deleted- boolean wf = false;- while (USAGE.allCount() < this.index) {- Handle h = new Handle(USAGE.allCount());- USAGE.FREEC++;- entryFile.writeInt(seekpos(h), USAGE.FREEH.index);- USAGE.FREEH = h;- wf = true;- }- assert (USAGE.allCount() >= this.index);-- // adopt USAGE.USEDC- if (USAGE.allCount() == this.index) {- USAGE.USEDC++;- wf = true;- }-- // commit changes- if (wf) {- USAGE.write();- entryFile.commit();- }- }+ //if ((USAGE != null) && (this.index != NUL)) USAGE.allocate(this.index);}public boolean isNUL() {diff --git a/source/de/anomic/kelondro/kelondroStack.java b/source/de/anomic/kelondro/kelondroStack.javaindex 5ab2fec20..14a5b2d48 100644--- a/source/de/anomic/kelondro/kelondroStack.java+++ b/source/de/anomic/kelondro/kelondroStack.java@@ -71,7 +71,7 @@ public final class kelondroStack extends kelondroRecords {// this creates a new stacksuper(file, 0, 0, thisOHBytes, thisOHHandles, rowdef, thisFHandles, rowdef.columns() /* txtProps */, 80 /* txtPropWidth */);if (super.fileExisted) {- if ((getHandle(root) == null) && (getHandle(toor) == null)) clear();+ //if ((getHandle(root) == null) && (getHandle(toor) == null)) clear();} else {setHandle(root, null); // define the root valuesetHandle(toor, null); // define the toor value@@ -106,12 +106,6 @@ public final class kelondroStack extends kelondroRecords {// re-open a database with same settings as beforereturn open(f, row);}-- public void clear() throws IOException {- super.clear();- setHandle(root, null); // reset the root value- setHandle(toor, null); // reset the toor value- }public class Counter implements Iterator {Handle nextHandle = null;@@ -127,8 +121,8 @@ public final class kelondroStack extends kelondroRecords {public Object next() {Handle ret = nextHandle;try {- nextHandle = getNode(nextHandle, null, 0).getOHHandle(right);- return getNode(ret, null, 0);+ nextHandle = getNode(nextHandle, null, 0, false).getOHHandle(right);+ return getNode(ret, null, 0, true);} catch (IOException e) {throw new kelondroException(filename, "IO error at Counter:next()");}@@ -139,13 +133,16 @@ public final class kelondroStack extends kelondroRecords {}}+ public synchronized int size() {+ return super.size();+ }+public synchronized void push(kelondroRow.Entry row) throws IOException {// check if there is already a stackif (getHandle(toor) == null) {if (getHandle(root) != null) throw new RuntimeException("push: internal organisation of root and toor");// create node- Node n = newNode();- n.setValueRow(row.bytes());+ Node n = newNode(row.bytes());n.setOHHandle(left, null);n.setOHHandle(right, null);n.commit(CP_NONE);@@ -155,11 +152,10 @@ public final class kelondroStack extends kelondroRecords {// thats it} else {// expand the list at the end- Node n = newNode();- n.setValueRow(row.bytes());+ Node n = newNode(row.bytes());n.setOHHandle(left, getHandle(toor));n.setOHHandle(right, null);- Node n1 = getNode(getHandle(toor), null, 0);+ Node n1 = getNode(getHandle(toor), null, 0, false);n1.setOHHandle(right, n.handle());n.commit(CP_NONE);n1.commit(CP_NONE);@@ -249,7 +245,7 @@ public final class kelondroStack extends kelondroRecords {setHandle(root, r);} else {// un-link the previous record- Node k = getNode(l, null, 0);+ Node k = getNode(l, null, 0, false);k.setOHHandle(left, k.getOHHandle(left));k.setOHHandle(right, r);k.commit(CP_NONE);@@ -260,7 +256,7 @@ public final class kelondroStack extends kelondroRecords {setHandle(toor, l);} else {// un-link the following record- Node k = getNode(r, null, 0);+ Node k = getNode(r, null, 0, false);k.setOHHandle(left, l);k.setOHHandle(right, k.getOHHandle(right));k.commit(CP_NONE);@@ -283,8 +279,8 @@ public final class kelondroStack extends kelondroRecords {Handle h = getHandle(side);if (h == null) return null;if (dist >= size()) return null; // that would exceed the stack- while (dist-- > 0) h = getNode(h).getOHHandle(dir); // track through elements- return getNode(h);+ while (dist-- > 0) h = getNode(h, false).getOHHandle(dir); // track through elements+ if (h == null) return null; else return getNode(h, true);}public Iterator iterator() {diff --git a/source/de/anomic/kelondro/kelondroTree.java b/source/de/anomic/kelondro/kelondroTree.javaindex 3d859c599..8e2b04544 100644--- a/source/de/anomic/kelondro/kelondroTree.java+++ b/source/de/anomic/kelondro/kelondroTree.java@@ -154,11 +154,6 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {super.setLogger(log);}- public void clear() throws IOException {- super.clear();- setHandle(root, null); // reset the root value- }-private void commitNode(Node n) throws IOException {Handle left = n.getOHHandle(leftchild);Handle right = n.getOHHandle(rightchild);@@ -235,7 +230,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {while (thisHandle != null) {try {parentnode = thenode;- thenode = getNode(thisHandle, thenode, (child == -1) ? leftchild : rightchild);+ thenode = getNode(thisHandle, thenode, (child == -1) ? leftchild : rightchild, true);} catch (IllegalArgumentException e) {logWarning("kelondroTree.Search.process: fixed a broken handle");found = false;@@ -338,8 +333,8 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {public kelondroRow.Entry put(kelondroRow.Entry newrow) throws IOException {assert (newrow != null);assert (newrow.columns() == row().columns());- assert (!(serverLog.allZero(newrow.getColBytes(ROW.primaryKey))));- assert newrow.bytes().length <= super.ROW.objectsize;+ assert (!(serverLog.allZero(newrow.getColBytes(super.row().primaryKey))));+ assert newrow.bytes().length <= super.row().objectsize;// Associates the specified value with the specified key in this mapkelondroRow.Entry result = null;//writeLock.stay(2000, 1000);@@ -357,8 +352,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {if (getHandle(root) != null)throw new kelondroException(filename, "tried to create root node twice");// we dont have any Nodes in the file, so start here to create one- Node e = newNode();- e.setValueRow(newrow.bytes());+ Node e = newNode(newrow.bytes());// write the propetriese.setOHByte(magic, (byte) 1);e.setOHByte(balance, (byte) 0);@@ -379,8 +373,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// create new node and assign valuesNode parentNode = writeSearchObj.getParent();- Node theNode = newNode();- theNode.setValueRow(newrow.bytes());+ Node theNode = newNode(newrow.bytes());theNode.setOHByte(0, (byte) 1); // fresh magictheNode.setOHByte(1, (byte) 0); // fresh balancetheNode.setOHHandle(parent, parentNode.handle());@@ -391,10 +384,10 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// check consistency and link new node to parent nodebyte parentBalance;if (writeSearchObj.isLeft()) {- if (parentNode.getOHHandle(leftchild) != null) throw new kelondroException(filename, "tried to create leftchild node twice. parent=" + new String(parentNode.getKey()) + ", leftchild=" + new String(new Node(parentNode.getOHHandle(leftchild), (Node) null, 0).getKey()));+ if (parentNode.getOHHandle(leftchild) != null) throw new kelondroException(filename, "tried to create leftchild node twice. parent=" + new String(parentNode.getKey()) + ", leftchild=" + new String(new Node(parentNode.getOHHandle(leftchild), (Node) null, 0, true).getKey()));parentNode.setOHHandle(leftchild, theNode.handle());} else if (writeSearchObj.isRight()) {- if (parentNode.getOHHandle(rightchild) != null) throw new kelondroException(filename, "tried to create rightchild node twice. parent=" + new String(parentNode.getKey()) + ", rightchild=" + new String(new Node(parentNode.getOHHandle(rightchild), (Node) null, 0).getKey()));+ if (parentNode.getOHHandle(rightchild) != null) throw new kelondroException(filename, "tried to create rightchild node twice. parent=" + new String(parentNode.getKey()) + ", rightchild=" + new String(new Node(parentNode.getOHHandle(rightchild), (Node) null, 0, true).getKey()));parentNode.setOHHandle(rightchild, theNode.handle());} else {throw new kelondroException(filename, "neither left nor right child");@@ -451,16 +444,16 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {}if (path.startsWith("RL")) {Handle parentHandle = parentNode.handle();- LL_RightRotation(theNode, getNode(theNode.getOHHandle(leftchild), theNode, leftchild));- parentNode = getNode(parentHandle, null, 0); // reload the parent node- RR_LeftRotation(parentNode, getNode(parentNode.getOHHandle(rightchild), parentNode, rightchild));+ LL_RightRotation(theNode, getNode(theNode.getOHHandle(leftchild), theNode, leftchild, false));+ parentNode = getNode(parentHandle, null, 0, false); // reload the parent node+ RR_LeftRotation(parentNode, getNode(parentNode.getOHHandle(rightchild), parentNode, rightchild, false));break;}if (path.startsWith("LR")) {Handle parentHandle = parentNode.handle();- RR_LeftRotation(theNode, getNode(theNode.getOHHandle(rightchild), theNode, rightchild));- parentNode = getNode(parentHandle, null, 0); // reload the parent node- LL_RightRotation(parentNode, getNode(parentNode.getOHHandle(leftchild), parentNode, leftchild));+ RR_LeftRotation(theNode, getNode(theNode.getOHHandle(rightchild), theNode, rightchild, false));+ parentNode = getNode(parentHandle, null, 0, false); // reload the parent node+ LL_RightRotation(parentNode, getNode(parentNode.getOHHandle(leftchild), parentNode, leftchild, false));break;}break;@@ -468,7 +461,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// crawl up the treeif (parentNode.getOHHandle(parent) == null) break; // root reached: stoptheNode = parentNode;- parentNode = getNode(parentNode.getOHHandle(parent), null, 0);+ parentNode = getNode(parentNode.getOHHandle(parent), null, 0, false);}result = null; // that means: no previous stored value present@@ -543,7 +536,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {private void LL_RightRotation(Node parentNode, Node childNode) throws IOException {// replace the parent node; the parent is afterwards unlinkedHandle p2Handle = parentNode.getOHHandle(parent);- Node p2Node = (p2Handle == null) ? null : getNode(p2Handle, null, 0);+ Node p2Node = (p2Handle == null) ? null : getNode(p2Handle, null, 0, false);replace(parentNode, p2Node, childNode);// set the left son of the parent to the right son of the childNode@@ -551,7 +544,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {if (childOfChild == null) {parentNode.setOHHandle(leftchild, null);} else {- assignChild(parentNode, getNode(childOfChild, childNode, rightchild), leftchild);+ assignChild(parentNode, getNode(childOfChild, childNode, rightchild, false), leftchild);}// link the old parent node as the right child of childNode@@ -574,7 +567,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {private void RR_LeftRotation(Node parentNode, Node childNode) throws IOException {// replace the parent node; the parent is afterwards unlinkedHandle p2Handle = parentNode.getOHHandle(parent);- Node p2Node = (p2Handle == null) ? null : getNode(p2Handle, null, 0);+ Node p2Node = (p2Handle == null) ? null : getNode(p2Handle, null, 0, false);replace(parentNode, p2Node, childNode);// set the left son of the parent to the right son of the childNode@@ -582,7 +575,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {if (childOfChild == null) {parentNode.setOHHandle(rightchild, null);} else {- assignChild(parentNode, getNode(childOfChild, childNode, leftchild), rightchild);+ assignChild(parentNode, getNode(childOfChild, childNode, leftchild, false), rightchild);}// link the old parent node as the left child of childNode@@ -661,12 +654,12 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {commitNode(parentOfNode);}} else if ((node.getOHHandle(leftchild) != null) && (node.getOHHandle(rightchild) == null)) {- replace(node, parentOfNode, getNode(node.getOHHandle(leftchild), node, leftchild));+ replace(node, parentOfNode, getNode(node.getOHHandle(leftchild), node, leftchild, false));} else if ((node.getOHHandle(leftchild) == null) && (node.getOHHandle(rightchild) != null)) {- replace(node, parentOfNode, getNode(node.getOHHandle(rightchild), node, rightchild));+ replace(node, parentOfNode, getNode(node.getOHHandle(rightchild), node, rightchild, false));} else {// difficult case: node has two children- Node repl = lastNode(getNode(node.getOHHandle(leftchild), node, leftchild));+ Node repl = lastNode(getNode(node.getOHHandle(leftchild), node, leftchild, false));//System.out.println("last node is " + repl.toString());// we remove that replacement node and put it where the node was// this seems to be recursive, but is not since the replacement@@ -676,7 +669,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// remove leafif ((repl.getOHHandle(leftchild) == null) && (repl.getOHHandle(rightchild) == null)) {// the replacement cannot be the root, so simply remove from parent node- n = getNode(repl.getOHHandle(parent), null, 0); // parent node of replacement node+ n = getNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement nodeh = n.getOHHandle(leftchild);if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);h = n.getOHHandle(rightchild);@@ -684,11 +677,11 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {commitNode(n);} else if ((repl.getOHHandle(leftchild) != null) && (repl.getOHHandle(rightchild) == null)) {try {- childnode = getNode(repl.getOHHandle(leftchild), repl, leftchild);- replace(repl, getNode(repl.getOHHandle(parent), null, 0), childnode);+ childnode = getNode(repl.getOHHandle(leftchild), repl, leftchild, false);+ replace(repl, getNode(repl.getOHHandle(parent), null, 0, false), childnode);} catch (IllegalArgumentException e) {// now treat the situation as if that link had been null before- n = getNode(repl.getOHHandle(parent), null, 0); // parent node of replacement node+ n = getNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement nodeh = n.getOHHandle(leftchild);if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);h = n.getOHHandle(rightchild);@@ -697,11 +690,11 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {}} else if ((repl.getOHHandle(leftchild) == null) && (repl.getOHHandle(rightchild) != null)) {try {- childnode = getNode(repl.getOHHandle(rightchild), repl, rightchild);- replace(repl, getNode(repl.getOHHandle(parent), null, 0), childnode);+ childnode = getNode(repl.getOHHandle(rightchild), repl, rightchild, false);+ replace(repl, getNode(repl.getOHHandle(parent), null, 0, false), childnode);} catch (IllegalArgumentException e) {// now treat the situation as if that link had been null before- n = getNode(repl.getOHHandle(parent), null, 0); // parent node of replacement node+ n = getNode(repl.getOHHandle(parent), null, 0, false); // parent node of replacement nodeh = n.getOHHandle(leftchild);if ((h != null) && (h.equals(repl.handle()))) n.setOHHandle(leftchild, null);h = n.getOHHandle(rightchild);@@ -710,7 +703,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {}}//System.out.println("node before reload is " + node.toString());- node = getNode(node.handle(), null, 0); // reload the node, it is possible that it has been changed+ node = getNode(node.handle(), null, 0, false); // reload the node, it is possible that it has been changed//System.out.println("node after reload is " + node.toString());// now plant in the replha node@@ -726,12 +719,12 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {commitNode(repl);// last thing to do: change uplinks of children to this new nodeif (leftchildHandle != null) {- n = getNode(leftchildHandle, node, leftchild);+ n = getNode(leftchildHandle, node, leftchild, false);n.setOHHandle(parent, repl.handle());commitNode(n);}if (rightchildHandle != null) {- n = getNode(rightchildHandle, node, rightchild);+ n = getNode(rightchildHandle, node, rightchild, false);n.setOHHandle(parent, repl.handle());commitNode(n);}@@ -745,7 +738,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {protected Node firstNode() throws IOException {Handle h = getHandle(root);if (h == null) return null;- return firstNode(getNode(h, null, 0));+ return firstNode(getNode(h, null, 0, true));}protected Node firstNode(Node node) throws IOException {@@ -755,7 +748,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {String nodeKey;while (h != null) {try {- node = getNode(h, node, leftchild);+ node = getNode(h, node, leftchild, true);nodeKey = new String(node.getKey());if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "firstNode: database contains loops: '" + nodeKey + "' appears twice.");visitedNodeKeys.add(nodeKey);@@ -771,7 +764,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {protected Node lastNode() throws IOException {Handle h = getHandle(root);if (h == null) return null;- return lastNode(getNode(h, null, 0));+ return lastNode(getNode(h, null, 0, true));}protected Node lastNode(Node node) throws IOException {@@ -781,7 +774,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {String nodeKey;while (h != null) {try {- node = getNode(h, node, rightchild);+ node = getNode(h, node, rightchild, true);nodeKey = new String(node.getKey());if (visitedNodeKeys.contains(nodeKey)) throw new kelondroException(this.filename, "lastNode: database contains loops: '" + nodeKey + "' appears twice.");visitedNodeKeys.add(nodeKey);@@ -836,7 +829,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// correct nextNode upon start// this happens, if the start node was not proper, or could not be foundwhile ((nextNode != null) && (nextNode.getKey() != null)) {- int c = ROW.objectOrder.compare(firstKey, nextNode.getKey());+ int c = row().objectOrder.compare(firstKey, nextNode.getKey());if (c == 0) {if (including) {break; // correct + finished@@ -871,10 +864,10 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {Handle searchHandle = getHandle(root);if (searchHandle == null) {nextNode = null; return;}- Node searchNode = getNode(searchHandle, null, 0);+ Node searchNode = getNode(searchHandle, null, 0, false);byte[] startKey = start.getKey();int c, ct;- while ((c = ROW.objectOrder.compare(startKey, searchNode.getKey())) != 0) {+ while ((c = row().objectOrder.compare(startKey, searchNode.getKey())) != 0) {// the current 'thisNode' is not the start node, put it on the stackct = (c < 0) ? leftchild : rightchild;nodeStack.addLast(new Object[]{searchNode, new Integer(ct)});@@ -882,7 +875,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// go to next nodesearchHandle = searchNode.getOHHandle(ct);if (searchHandle == null) throw new kelondroException(filename, "nodeIterator.init: start node does not exist (handle null)");- searchNode = getNode(searchHandle, searchNode, ct);+ searchNode = getNode(searchHandle, searchNode, ct, false);if (searchNode == null) throw new kelondroException(filename, "nodeIterator.init: start node does not exist (node null)");}// now every parent node to the start node is on the stack@@ -917,7 +910,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {// we have walked one leg of the tree; now go to the other one: step down to next childHashSet visitedNodeHandles = new HashSet(); // to detect loopsnodeStack.addLast(new Object[]{nextNode, new Integer(childtype)});- nextNode = getNode(childHandle, nextNode, childtype);+ nextNode = getNode(childHandle, nextNode, childtype, false);childtype = (up) ? leftchild : rightchild;while ((childHandle = nextNode.getOHHandle(childtype)) != null) {if (visitedNodeHandles.contains(childHandle)) {@@ -930,7 +923,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {visitedNodeHandles.add(childHandle);try {nodeStack.addLast(new Object[]{nextNode, new Integer(childtype)});- nextNode = getNode(childHandle, nextNode, childtype);+ nextNode = getNode(childHandle, nextNode, childtype, false);} catch (IllegalArgumentException e) {// return what we havenodeStack.removeLast();@@ -978,7 +971,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {public TreeMap rowMap(boolean up, boolean rotating, byte[] firstKey, boolean including, int count) throws IOException {// returns an ordered map of keys/row relations; key objects are of type String, value objects are of type byte[][]- kelondroOrder setOrder = (kelondroOrder) ROW.objectOrder.clone();+ kelondroOrder setOrder = (kelondroOrder) row().objectOrder.clone();setOrder.direction(up);setOrder.rotate(firstKey);TreeMap rows = new TreeMap(setOrder);@@ -998,7 +991,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {public TreeSet keySet(boolean up, boolean rotating, byte[] firstKey, boolean including, int count) throws IOException {// returns an ordered set of keys; objects are of type String- kelondroOrder setOrder = (kelondroOrder) ROW.objectOrder.clone();+ kelondroOrder setOrder = (kelondroOrder) row().objectOrder.clone();setOrder.direction(up);setOrder.rotate(firstKey);TreeSet set = new TreeSet(setOrder);@@ -1119,7 +1112,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {try {Handle h = getHandle(root);if (h == null) return 0;- return height(getNode(h, null, 0));+ return height(getNode(h, null, 0, false));} catch (IOException e) {return 0;}@@ -1128,18 +1121,13 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {private int height(Node node) throws IOException {if (node == null) return 0;Handle h = node.getOHHandle(leftchild);- int hl = (h == null) ? 0 : height(getNode(h, node, leftchild));+ int hl = (h == null) ? 0 : height(getNode(h, node, leftchild, false));h = node.getOHHandle(rightchild);- int hr = (h == null) ? 0 : height(getNode(h, node, rightchild));+ int hr = (h == null) ? 0 : height(getNode(h, node, rightchild, false));if (hl > hr) return hl + 1;return hr + 1;}- /*- public String np(Object n) {- if (n == null) return "NULL";- return n.toString();- }- */+public void print() throws IOException {super.print(false);int height = height();@@ -1160,7 +1148,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {node = null;key = "[..]";} else {- node = getNode(handle, null, 0);+ node = getNode(handle, null, 0, false);if (node == null) key = "NULL"; else key = new String(node.getKey());}System.out.print(key);@@ -1195,7 +1183,7 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {node = null;key = "NULL";} else {- node = getNode(handle, null, 0);+ node = getNode(handle, null, 0, false);if (node == null) key = "NULL"; else key = new String(node.getKey());}System.out.print(key);@@ -1317,8 +1305,8 @@ public class kelondroTree extends kelondroRecords implements kelondroIndex {//cmd(args);//iterationtest();//bigtest(Integer.parseInt(args[0]));- //randomtest(Integer.parseInt(args[0]));- smalltest();+ randomtest(Integer.parseInt(args[0]));+ //smalltest();}public static String[] permutations(int letters) {diff --git a/source/de/anomic/plasma/plasmaCrawlBalancer.java b/source/de/anomic/plasma/plasmaCrawlBalancer.javaindex 4f18e2231..1aba9b9ba 100644--- a/source/de/anomic/plasma/plasmaCrawlBalancer.java+++ b/source/de/anomic/plasma/plasmaCrawlBalancer.java@@ -107,7 +107,9 @@ public class plasmaCrawlBalancer {while (i.hasNext()) {entry = (Map.Entry) i.next();list = (ArrayList) entry.getValue();- stack.push(stack.row().newEntry(new byte[][]{(byte[]) list.remove(0)}));+ if (list.size() != 0) {+ stack.push(stack.row().newEntry(new byte[][]{(byte[]) list.remove(0)}));+ }if (list.size() == 0) i.remove();}}@@ -144,11 +146,13 @@ public class plasmaCrawlBalancer {if (stack.size() == 0) return null;String entry = null;- String topentry = new String(stack.top().getColBytes(0));+ kelondroRow.Entry topentry = stack.top();+ if (topentry == null) return null;+ String top = new String(topentry.getColBytes(0));// check if the time after retrieval of last hash from same// domain is not shorter than the minimumDelta- long delta = lastAccessDelta(topentry);+ long delta = lastAccessDelta(top);if (delta > minimumDelta) {// the entry from top is fineentry = new String(stack.pop().getColBytes(0));@@ -188,7 +192,7 @@ public class plasmaCrawlBalancer {public void clear() throws IOException {synchronized (domainStacks) {domainStacks.clear();- stack.clear();+ stack = kelondroStack.reset(stack);}}diff --git a/source/de/anomic/plasma/plasmaCrawlNURL.java b/source/de/anomic/plasma/plasmaCrawlNURL.javaindex 1e42d82b1..29bbcd142 100644--- a/source/de/anomic/plasma/plasmaCrawlNURL.java+++ b/source/de/anomic/plasma/plasmaCrawlNURL.java@@ -411,9 +411,9 @@ public class plasmaCrawlNURL {case STACK_TYPE_LIMIT: limitStack.clear(); break;case STACK_TYPE_OVERHANG: overhangStack.clear(); break;case STACK_TYPE_REMOTE: remoteStack.clear(); break;- case STACK_TYPE_IMAGE: imageStack.clear(); break;- case STACK_TYPE_MOVIE: movieStack.clear(); break;- case STACK_TYPE_MUSIC: musicStack.clear(); break;+ case STACK_TYPE_IMAGE: imageStack = kelondroStack.reset(imageStack); break;+ case STACK_TYPE_MOVIE: movieStack = kelondroStack.reset(movieStack); break;+ case STACK_TYPE_MUSIC: musicStack = kelondroStack.reset(musicStack); break;default: return;}} catch (IOException e) {}diff --git a/source/de/anomic/plasma/plasmaSwitchboardQueue.java b/source/de/anomic/plasma/plasmaSwitchboardQueue.javaindex e3c862501..a909c8931 100644--- a/source/de/anomic/plasma/plasmaSwitchboardQueue.java+++ b/source/de/anomic/plasma/plasmaSwitchboardQueue.java@@ -157,7 +157,7 @@ public class plasmaSwitchboardQueue {}public void clear() throws IOException {- sbQueueStack.clear();+ sbQueueStack = kelondroStack.reset(sbQueueStack);}public void close() {diff --git a/source/de/anomic/server/logging/serverLog.java b/source/de/anomic/server/logging/serverLog.javaindex e0e54eeff..4e126b328 100644--- a/source/de/anomic/server/logging/serverLog.java+++ b/source/de/anomic/server/logging/serverLog.java@@ -234,7 +234,7 @@ public final class serverLog {StringBuffer sb = new StringBuffer(b.length * 4);for (int i = 0; i < b.length; i++) {if (i % linewidth == 0)- sb.append('\n').append("# ").append(Integer.toHexString(i));+ sb.append('\n').append("# ").append(Integer.toHexString(i)).append(": ");elsesb.append(',');sb.append(' ').append(Integer.toString(0xff & (int) b[i]));diff --git a/source/de/anomic/yacy/yacyNewsPool.java b/source/de/anomic/yacy/yacyNewsPool.javaindex 22cf08f62..c7a604100 100644--- a/source/de/anomic/yacy/yacyNewsPool.java+++ b/source/de/anomic/yacy/yacyNewsPool.java@@ -139,7 +139,7 @@ public class yacyNewsPool {// generate a record for next peer-pingif (outgoingNews.size() == 0) return null;yacyNewsRecord record = outgoingNews.topInc();- if (record.distributed() >= maxDistribution) {+ if ((record != null) && (record.distributed() >= maxDistribution)) {// move record to its final position. This is only for historypublishedNews.push(outgoingNews.pop(0));}diff --git a/yacy.init b/yacy.initindex c30701dc5..4e329d63c 100644--- a/yacy.init+++ b/yacy.init@@ -479,8 +479,8 @@ xpstopw=true40_peerseedcycle_idlesleep=180000040_peerseedcycle_busysleep=120000040_peerseedcycle_memprereq=2097152-50_localcrawl_idlesleep=10000-50_localcrawl_busysleep=300+50_localcrawl_idlesleep=1000+50_localcrawl_busysleep=12050_localcrawl_memprereq=209715250_localcrawl_isPaused=false61_globalcrawltrigger_idlesleep=10000@@ -491,11 +491,11 @@ xpstopw=true62_remotetriggeredcrawl_busysleep=100062_remotetriggeredcrawl_memprereq=419430462_remotetriggeredcrawl_isPaused=false-70_cachemanager_idlesleep=5000+70_cachemanager_idlesleep=100070_cachemanager_busysleep=070_cachemanager_memprereq=104857680_indexing_idlesleep=2000-80_indexing_busysleep=200+80_indexing_busysleep=10080_indexing_memprereq=209715282_crawlstack_idlesleep=500082_crawlstack_busysleep=0@@ -594,8 +594,8 @@ javastart_priority=0# may last for the word flushwordCacheMaxCount = 20000wordCacheInitCount = 30000-wordFlushIdleDivisor = 500;-wordFlushBusyDivisor = 5000;+wordFlushIdleDivisor = 400;+wordFlushBusyDivisor = 4000;# Specifies if yacy can be used as transparent http proxy.#@@ -655,14 +655,14 @@ crawler.clientTimeout=9000crawler.http.acceptEncoding=gzipcrawler.http.acceptLanguage=en-us,en;q=0.5crawler.http.acceptCharset=ISO-8859-1,utf-8;q=0.7,*;q=0.7-crawler.http.maxFileSize=-1+crawler.http.maxFileSize=262144# ftp crawler specific settings-crawler.ftp.maxFileSize=-1+crawler.ftp.maxFileSize=262144# maximum number of crawler threads-crawler.MaxActiveThreads = 10-crawler.MaxIdleThreads = 7+crawler.MaxActiveThreads = 30+crawler.MaxIdleThreads = 5# maximum number of crawl-stacker threadsstacker.MaxActiveThreads = 50@@ -670,7 +670,7 @@ stacker.MaxIdleThreads = 10stacker.MinIdleThreads = 5# maximum size of indexing queue-indexer.slots = 30+indexer.slots = 60# specifies if yacy should set it's own referer if no referer URL# was set by the client.