Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

a collection of performance hacks and code cleanup: - removed usage of URL-Caches which could have been a memory leak - removed unused classes and methods - removed not necessary synchronizations - added synchronization hacks where possible - fine-tuned crawling speed to prevent IO of balancer - fixed a bug in IODispatcher that may have caused that no merges were done - reduced number of parameters in very often called methods (compare methods) - reduced complexity of data structures of now massively used HandleSet class - reduction of new String() and getBytes() usage / new methods to support this transition

orbiter64f29f990e39
diff --git a/source/de/anomic/crawler/CrawlProfile.java b/source/de/anomic/crawler/CrawlProfile.java
index 2727a2df0..b530748b2 100644
--- a/source/de/anomic/crawler/CrawlProfile.java
+++ b/source/de/anomic/crawler/CrawlProfile.java
@@ -212,6 +212,7 @@ public class CrawlProfile {
}
public entry getEntry(final String handle) {
+ if (profileTable == null) return null;
Map<String, String> m;
try {
m = profileTable.get(handle);
diff --git a/source/de/anomic/crawler/ZURL.java b/source/de/anomic/crawler/ZURL.java
index e47232d32..0f37fe494 100755
--- a/source/de/anomic/crawler/ZURL.java
+++ b/source/de/anomic/crawler/ZURL.java
@@ -284,12 +284,12 @@ public class ZURL implements Iterable<ZURL.Entry> {
}
- public class kiter implements Iterator<Entry> {
+ private class kiter implements Iterator<Entry> {
// enumerates entry elements
- Iterator<Row.Entry> i;
- boolean error = false;
+ private Iterator<Row.Entry> i;
+ private boolean error = false;
- public kiter(final boolean up, final String firstHash) throws IOException {
+ private kiter(final boolean up, final String firstHash) throws IOException {
i = urlIndex.rows(up, (firstHash == null) ? null : firstHash.getBytes());
error = false;
}
diff --git a/source/de/anomic/data/URLAnalysis.java b/source/de/anomic/data/URLAnalysis.java
index ceb874b0e..86b1a8856 100644
--- a/source/de/anomic/data/URLAnalysis.java
+++ b/source/de/anomic/data/URLAnalysis.java
@@ -415,7 +415,7 @@ public class URLAnalysis {
public static int diffurlcol(final String metadataPath, final String statisticFile, final String diffFile) throws IOException, RowSpaceExceededException {
System.out.println("INDEX DIFF URL-COL startup");
- final HandleMap idx = new HandleMap(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 4, new File(statisticFile), 0);
+ final HandleMap idx = new HandleMap(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 4, new File(statisticFile));
final MetadataRepository mr = new MetadataRepository(new File(metadataPath), "text.urlmd", false, false);
final HandleSet hs = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, 1000000);
System.out.println("INDEX DIFF URL-COL loaded dump, starting diff");
@@ -444,7 +444,7 @@ public class URLAnalysis {
// format: 0=text, 1=html, 2=rss/xml
System.out.println("URL EXPORT startup");
final MetadataRepository mr = new MetadataRepository(new File(metadataPath), "text.urlmd", false, false);
- final HandleSet hs = (diffFile == null) ? null : new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, new File(diffFile), 0);
+ final HandleSet hs = (diffFile == null) ? null : new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, new File(diffFile));
System.out.println("URL EXPORT loaded dump, starting export");
final Export e = mr.export(new File(export), ".*", hs, format, false);
try {
@@ -459,7 +459,7 @@ public class URLAnalysis {
System.out.println("URL DELETE startup");
final MetadataRepository mr = new MetadataRepository(new File(metadataPath), "text.urlmd", false, false);
final int mrSize = mr.size();
- final HandleSet hs = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, new File(diffFile), 0);
+ final HandleSet hs = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.objectOrder, new File(diffFile));
System.out.println("URL DELETE loaded dump, starting deletion of " + hs.size() + " entries from " + mrSize);
for (final byte[] refhash: hs) {
mr.remove(refhash);
diff --git a/source/de/anomic/search/MetadataRepository.java b/source/de/anomic/search/MetadataRepository.java
index 6cf2eb7bd..2e7954d12 100644
--- a/source/de/anomic/search/MetadataRepository.java
+++ b/source/de/anomic/search/MetadataRepository.java
@@ -81,7 +81,7 @@ public final class MetadataRepository implements Iterable<byte[]> {
Log.logException(e1);
}
}
- this.urlIndexFile = new Cache(backupIndex, 20000000, 20000000);
+ this.urlIndexFile = backupIndex; //new Cache(backupIndex, 20000000, 20000000);
this.exportthread = null; // will have a export thread assigned if exporter is running
this.statsDump = null;
}
@@ -120,6 +120,7 @@ public final class MetadataRepository implements Iterable<byte[]> {
// if the url cannot be found, this returns null
if (urlHash == null) return null;
assert urlIndexFile != null : "urlHash = " + new String(urlHash);
+ if (urlIndexFile == null) return null;
try {
final Row.Entry entry = urlIndexFile.get(urlHash);
if (entry == null) return null;
@@ -132,7 +133,6 @@ public final class MetadataRepository implements Iterable<byte[]> {
public void store(final URIMetadataRow entry) throws IOException {
// Check if there is a more recent Entry already in the DB
URIMetadataRow oldEntry;
- synchronized (this) {
try {
Row.Entry oe = (urlIndexFile == null) ? null : urlIndexFile.get(entry.hash());
oldEntry = (oe == null) ? null : new URIMetadataRow(oe, null, 0);
@@ -154,7 +154,6 @@ public final class MetadataRepository implements Iterable<byte[]> {
} catch (RowSpaceExceededException e) {
throw new IOException("RowSpaceExceededException in " + this.urlIndexFile.filename() + ": " + e.getMessage());
}
- }
statsDump = null;
}
diff --git a/source/de/anomic/search/QueryParams.java b/source/de/anomic/search/QueryParams.java
index ddd8cca89..d54e2d01c 100644
--- a/source/de/anomic/search/QueryParams.java
+++ b/source/de/anomic/search/QueryParams.java
@@ -26,7 +26,6 @@
package de.anomic.search;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.regex.Pattern;
@@ -62,7 +61,6 @@ public final class QueryParams {
}
public static final Bitfield empty_constraint = new Bitfield(4, "AAAAAA");
- public static final Bitfield catchall_constraint = new Bitfield(4, "______");
public static final Pattern catchall_pattern = Pattern.compile(".*");
public static final Pattern matchnothing_pattern = Pattern.compile("");
@@ -235,15 +233,6 @@ public final class QueryParams {
return keyhashes;
}
- public static HashSet<String> hashes2StringSet(final String query) {
- if (query == null) return new HashSet<String>();
- final HashSet<String> keyhashes = new HashSet<String>();
- for (int i = 0; i < (query.length() / Word.commonHashLength); i++) {
- keyhashes.add(query.substring(i * Word.commonHashLength, (i + 1) * Word.commonHashLength));
- }
- return keyhashes;
- }
-
public static HandleSet hashes2Handles(final String query) {
final HandleSet keyhashes = new HandleSet(WordReferenceRow.urlEntryRow.primaryKeyLength, WordReferenceRow.urlEntryRow.objectOrder, 0);
if (query == null) return keyhashes;
@@ -254,18 +243,7 @@ public final class QueryParams {
}
return keyhashes;
}
- /*
- public static String hashSet2hashString(final TreeSet<byte[]> hashes) {
- final byte[] bb = new byte[hashes.size() * Word.commonHashLength];
- int p = 0;
- for (byte[] b : hashes) {
- assert b.length == Word.commonHashLength : "hash = " + new String(b);
- System.arraycopy(b, 0, bb, p, Word.commonHashLength);
- p += Word.commonHashLength;
- }
- return new String(bb);
- }
- */
+
public static String hashSet2hashString(final HandleSet hashes) {
final byte[] bb = new byte[hashes.size() * Word.commonHashLength];
int p = 0;
@@ -295,7 +273,7 @@ public final class QueryParams {
return new String(sb);
}
- public static final boolean matches(final String text, final HandleSet keyhashes) {
+ protected static final boolean matches(final String text, final HandleSet keyhashes) {
// returns true if any of the word hashes in keyhashes appear in the String text
// to do this, all words in the string must be recognized and transcoded to word hashes
final HandleSet wordhashes = Word.words2hashesHandles(Condenser.getWords(text).keySet());
diff --git a/source/de/anomic/search/RankingProcess.java b/source/de/anomic/search/RankingProcess.java
index 6dd66cf10..edc4f7ea8 100644
--- a/source/de/anomic/search/RankingProcess.java
+++ b/source/de/anomic/search/RankingProcess.java
@@ -32,7 +32,6 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -63,7 +62,7 @@ import de.anomic.yacy.graphics.ProfilingGraph;
public final class RankingProcess extends Thread {
public static BinSearch[] ybrTables = null; // block-rank tables
- public static final int maxYBR = 3; // the lower this value, the faster the search
+ private static final int maxYBR = 3; // the lower this value, the faster the search
private static boolean useYBR = true;
private static final int maxDoubleDomAll = 100, maxDoubleDomSpecial = 10000;
@@ -80,7 +79,7 @@ public final class RankingProcess extends Thread {
private final SortStack<WordReferenceVars> stack;
private int feeders;
private final ConcurrentHashMap<String, SortStack<WordReferenceVars>> doubleDomCache; // key = domhash (6 bytes); value = like stack
- private final HashSet<String> handover; // key = urlhash; used for double-check of urls that had been handed over to search process
+ //private final HandleSet handover; // key = urlhash; used for double-check of urls that had been handed over to search process
private final Navigator ref; // reference score computation for the commonSense heuristic
private final Navigator hostNavigator;
@@ -95,7 +94,7 @@ public final class RankingProcess extends Thread {
this.localSearchInclusion = null;
this.stack = new SortStack<WordReferenceVars>(maxentries, true);
this.doubleDomCache = new ConcurrentHashMap<String, SortStack<WordReferenceVars>>();
- this.handover = new HashSet<String>();
+ //this.handover = new HandleSet(URIMetadataRow.rowdef.primaryKeyLength, URIMetadataRow.rowdef.getOrdering(), 0);
this.query = query;
this.order = order;
this.maxentries = maxentries;
@@ -277,11 +276,11 @@ public final class RankingProcess extends Thread {
assert this.feeders >= 0 : "feeders = " + this.feeders;
}
- public void moreFeeders(final int countMoreFeeders) {
+ protected void moreFeeders(final int countMoreFeeders) {
this.feeders += countMoreFeeders;
}
- public boolean feedingIsFinished() {
+ private boolean feedingIsFinished() {
return this.feeders == 0;
}
@@ -302,7 +301,7 @@ public final class RankingProcess extends Thread {
return false;
}
- public Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {
+ protected Map<byte[], ReferenceContainer<WordReference>> searchContainerMap() {
// direct access to the result maps is needed for abstract generation
// this is only available if execQuery() was called before
return localSearchInclusion;
@@ -481,14 +480,19 @@ public final class RankingProcess extends Thread {
}
// accept url
- //System.out.println("handing over hash " + page.hash());
- this.handover.add(new String(page.hash())); // remember that we handed over this url
+ /*
+ try {
+ this.handover.put(page.hash()); // remember that we handed over this url
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ }
+ */
return page;
}
return null;
}
- public int size() {
+ protected int size() {
//assert sortedRWIEntries.size() == urlhashes.size() : "sortedRWIEntries.size() = " + sortedRWIEntries.size() + ", urlhashes.size() = " + urlhashes.size();
int c = stack.size();
for (SortStack<WordReferenceVars> s: this.doubleDomCache.values()) {
@@ -541,7 +545,7 @@ public final class RankingProcess extends Thread {
return this.remote_peerCount;
}
- public void remove(final WordReferenceVars reference) {
+ protected void remove(final WordReferenceVars reference) {
stack.remove(reference);
urlhashes.remove(reference.urlHash);
}
@@ -587,7 +591,6 @@ public final class RankingProcess extends Thread {
return result;
}
-
public static final Comparator<Map.Entry<String, Integer>> mecomp = new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if (o1.getValue().intValue() < o2.getValue().intValue()) return 1;
diff --git a/source/de/anomic/yacy/dht/PeerSelection.java b/source/de/anomic/yacy/dht/PeerSelection.java
index 9b7b5f0e7..f89028b24 100755
--- a/source/de/anomic/yacy/dht/PeerSelection.java
+++ b/source/de/anomic/yacy/dht/PeerSelection.java
@@ -26,10 +26,11 @@ package de.anomic.yacy.dht;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import net.yacy.kelondro.data.word.Word;
+import net.yacy.kelondro.index.HandleSet;
+import net.yacy.kelondro.index.RowSpaceExceededException;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.order.Digest;
@@ -90,7 +91,7 @@ public class PeerSelection {
}
- public static boolean guessIfOwnWord(final yacySeedDB seedDB, final byte[] wordhash, final String urlhash) {
+ private static boolean guessIfOwnWord(final yacySeedDB seedDB, final byte[] wordhash, final String urlhash) {
if (seedDB == null) return false;
int connected = seedDB.sizeConnected();
if (connected == 0) return true;
@@ -102,7 +103,7 @@ public class PeerSelection {
return false;
}
- public static boolean verifyIfOwnWord(final yacySeedDB seedDB, byte[] wordhash, String urlhash, int redundancy) {
+ private static boolean verifyIfOwnWord(final yacySeedDB seedDB, byte[] wordhash, String urlhash, int redundancy) {
String myHash = seedDB.mySeed().hash;
wordhash = FlatWordPartitionScheme.positionToHash(seedDB.scheme.dhtPosition(wordhash, urlhash));
Iterator<yacySeed> dhtEnum = getAcceptRemoteIndexSeeds(seedDB, wordhash, redundancy, true);
@@ -122,7 +123,7 @@ public class PeerSelection {
return null;
}
- public static ArrayList<yacySeed> getAcceptRemoteIndexSeedsList(
+ protected static ArrayList<yacySeed> getAcceptRemoteIndexSeedsList(
yacySeedDB seedDB,
final byte[] starthash,
int max,
@@ -151,7 +152,7 @@ public class PeerSelection {
private final Iterator<yacySeed> se;
private yacySeed nextSeed;
private final yacySeedDB seedDB;
- private final HashSet<String> doublecheck;
+ private final HandleSet doublecheck;
private int remaining;
private boolean alsoMyOwn;
@@ -159,7 +160,7 @@ public class PeerSelection {
this.seedDB = seedDB;
this.se = getDHTSeeds(seedDB, starthash, yacyVersion.YACY_HANDLES_COLLECTION_INDEX);
this.remaining = max;
- this.doublecheck = new HashSet<String>();
+ this.doublecheck = new HandleSet(12, Base64Order.enhancedCoder, 0);
this.nextSeed = nextInternal();
this.alsoMyOwn = alsoMyOwn && nextSeed != null && (Base64Order.enhancedCoder.compare(seedDB.mySeed().hash.getBytes(), nextSeed.hash.getBytes()) > 0);
}
@@ -175,8 +176,14 @@ public class PeerSelection {
while (se.hasNext()) {
s = se.next();
if (s == null) return null;
- if (doublecheck.contains(s.hash)) return null;
- this.doublecheck.add(s.hash);
+ byte[] hashb = s.hash.getBytes();
+ if (doublecheck.has(hashb)) return null;
+ try {
+ this.doublecheck.put(hashb);
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ break;
+ }
if (s.getFlagAcceptRemoteIndex()) {
this.remaining--;
return s;
diff --git a/source/de/anomic/yacy/yacyPeerActions.java b/source/de/anomic/yacy/yacyPeerActions.java
index 018359b1d..abf562844 100644
--- a/source/de/anomic/yacy/yacyPeerActions.java
+++ b/source/de/anomic/yacy/yacyPeerActions.java
@@ -206,7 +206,7 @@ public class yacyPeerActions {
// we do this if we did not get contact with the other peer
if (yacyCore.log.isFine()) yacyCore.log.logFine("connect: no contact to a " + peer.get(yacySeed.PEERTYPE, yacySeed.PEERTYPE_VIRGIN) + " peer '" + peer.getName() + "' at " + peer.getPublicAddress() + ". Cause: " + cause);
synchronized (seedDB) {
- if (!seedDB.hasDisconnected(peer.hash)) { disconnects++; }
+ if (!seedDB.hasDisconnected(peer.hash.getBytes())) { disconnects++; }
peer.put("dct", Long.toString(System.currentTimeMillis()));
seedDB.addDisconnected(peer); // update info
}
diff --git a/source/de/anomic/yacy/yacySeed.java b/source/de/anomic/yacy/yacySeed.java
index 791c6c866..44feff07b 100644
--- a/source/de/anomic/yacy/yacySeed.java
+++ b/source/de/anomic/yacy/yacySeed.java
@@ -109,24 +109,24 @@ public class yacySeed implements Cloneable {
public static final String PEERTYPE = "PeerType";
/** static/dynamic (if the IP changes often for any reason) */
- public static final String IPTYPE = "IPType";
- public static final String FLAGS = "Flags";
- public static final String FLAGSZERO = "____";
+ private static final String IPTYPE = "IPType";
+ private static final String FLAGS = "Flags";
+ private static final String FLAGSZERO = "____";
/** the applications version */
- public static final String VERSION = "Version";
+ public static final String VERSION = "Version";
- public static final String YOURTYPE = "yourtype";
- public static final String LASTSEEN = "LastSeen";
- public static final String USPEED = "USpeed";
+ public static final String YOURTYPE = "yourtype";
+ public static final String LASTSEEN = "LastSeen";
+ private static final String USPEED = "USpeed";
/** the name of the peer (user-set) */
- public static final String NAME = "Name";
- public static final String HASH = "Hash";
+ public static final String NAME = "Name";
+ private static final String HASH = "Hash";
/** Birthday - first startup */
- public static final String BDATE = "BDate";
+ private static final String BDATE = "BDate";
/** UTC-Offset */
- public static final String UTC = "UTC";
- public static final String PEERTAGS = "Tags";
+ public static final String UTC = "UTC";
+ private static final String PEERTAGS = "Tags";
/** the speed of indexing (pages/minute) of the peer */
public static final String ISPEED = "ISpeed";
@@ -154,7 +154,7 @@ public class yacySeed implements Cloneable {
public static final String PORT = "Port";
public static final String SEEDLIST = "seedURL";
/** zero-value */
- public static final String ZERO = "0";
+ private static final String ZERO = "0";
private static final int FLAG_DIRECT_CONNECT = 0;
private static final int FLAG_ACCEPT_REMOTE_CRAWL = 1;
@@ -171,9 +171,8 @@ public class yacySeed implements Cloneable {
public String hash;
/** a set of identity founding values, eg. IP, name of the peer, YaCy-version, ...*/
private final ConcurrentHashMap<String, String> dna;
- public int available;
- public int selectscore = -1; // only for debugging
- public String alternativeIP = null;
+ protected int selectscore = -1; // only for debugging
+ private String alternativeIP = null;
public yacySeed(final String theHash, final ConcurrentHashMap<String, String> theDna) {
// create a seed with a pre-defined hash map
@@ -182,11 +181,10 @@ public class yacySeed implements Cloneable {
this.dna = theDna;
final String flags = this.dna.get(yacySeed.FLAGS);
if ((flags == null) || (flags.length() != 4)) { this.dna.put(yacySeed.FLAGS, yacySeed.FLAGSZERO); }
- this.available = 0;
this.dna.put(yacySeed.NAME, checkPeerName(get(yacySeed.NAME, "&empty;")));
}
- public yacySeed(final String theHash) {
+ private yacySeed(final String theHash) {
this.dna = new ConcurrentHashMap<String, String>();
// settings that can only be computed by originating peer:
@@ -233,8 +231,6 @@ public class yacySeed implements Cloneable {
this.dna.put(yacySeed.INDEX_IN, yacySeed.ZERO); // received index
this.dna.put(yacySeed.URL_OUT, yacySeed.ZERO); // send URLs
this.dna.put(yacySeed.URL_IN, yacySeed.ZERO); // received URLs
-
- this.available = 0;
}
/**
@@ -419,25 +415,6 @@ public class yacySeed implements Cloneable {
public static String hexHash2b64Hash(final String hexHash) {
return Base64Order.enhancedCoder.encode(Digest.decodeHex(hexHash));
}
-
- /**
- * <code>12 * 6 bit = 72 bit = 9 byte</code>
- * @param b64Hash a base64 hash
- * @return returns a base256 - a byte - representation of the given base64 hash
- */
- public static byte[] b64Hash2b256Hash(final String b64Hash) {
- assert b64Hash.length() == 12;
- return Base64Order.enhancedCoder.decode(b64Hash);
- }
-
- /**
- * @param b256Hash a base256 hash - normal byte number system
- * @return the base64 representation of the given base256 hash
- */
- public static String b256Hash2b64Hash(final byte[] b256Hash) {
- assert b256Hash.length == 9;
- return Base64Order.enhancedCoder.encode(b256Hash);
- }
/**
* The returned version follows this pattern: <code>MAJORVERSION . MINORVERSION 0 SVN REVISION</code>
diff --git a/source/de/anomic/yacy/yacySeedDB.java b/source/de/anomic/yacy/yacySeedDB.java
index 9a372d7c1..d73eddda1 100644
--- a/source/de/anomic/yacy/yacySeedDB.java
+++ b/source/de/anomic/yacy/yacySeedDB.java
@@ -33,7 +33,6 @@ import java.lang.ref.SoftReference;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
-import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
@@ -43,6 +42,8 @@ import java.util.concurrent.ConcurrentHashMap;
import net.yacy.kelondro.blob.MapDataMining;
import net.yacy.kelondro.data.meta.DigestURI;
import net.yacy.kelondro.data.word.Word;
+import net.yacy.kelondro.index.HandleSet;
+import net.yacy.kelondro.index.RowSpaceExceededException;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.Base64Order;
import net.yacy.kelondro.util.FileUtils;
@@ -65,7 +66,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
// global statics
- public static final int dhtActivityMagic = 32;
+ private static final int dhtActivityMagic = 32;
/**
* <p><code>public static final String <strong>DBFILE_OWN_SEED</strong> = "mySeed.txt"</code></p>
@@ -78,13 +79,13 @@ public final class yacySeedDB implements AlternativeDomainNames {
public static final String[] doubleaccFields = new String[] {yacySeed.RSPEED};
// class objects
- protected File seedActiveDBFile, seedPassiveDBFile, seedPotentialDBFile;
- protected File myOwnSeedFile;
- protected MapDataMining seedActiveDB, seedPassiveDB, seedPotentialDB;
+ private File seedActiveDBFile, seedPassiveDBFile, seedPotentialDBFile;
+ private File myOwnSeedFile;
+ private MapDataMining seedActiveDB, seedPassiveDB, seedPotentialDB;
- public int lastSeedUpload_seedDBSize = 0;
+ protected int lastSeedUpload_seedDBSize = 0;
public long lastSeedUpload_timeStamp = System.currentTimeMillis();
- public String lastSeedUpload_myIP = "";
+ protected String lastSeedUpload_myIP = "";
public yacyPeerActions peerActions;
public yacyNewsPool newsPool;
@@ -273,7 +274,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
} catch (final IOException e) { Log.logWarning("yacySeedDB", "could not remove hash ("+ e.getClass() +"): "+ e.getMessage()); }
}
- public void saveMySeed() {
+ protected void saveMySeed() {
try {
this.mySeed().save(myOwnSeedFile);
} catch (final IOException e) { Log.logWarning("yacySeedDB", "could not save mySeed '"+ myOwnSeedFile +"': "+ e.getMessage()); }
@@ -305,7 +306,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
}
- protected synchronized MapDataMining resetSeedTable(MapDataMining seedDB, final File seedDBFile) {
+ private synchronized MapDataMining resetSeedTable(MapDataMining seedDB, final File seedDBFile) {
// this is an emergency function that should only be used if any problem with the
// seed.db is detected
yacyCore.log.logWarning("seed-db " + seedDBFile.toString() + " reset (on-the-fly)");
@@ -319,8 +320,8 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
public synchronized void resetActiveTable() { seedActiveDB = resetSeedTable(seedActiveDB, seedActiveDBFile); }
- public synchronized void resetPassiveTable() { seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile); }
- public synchronized void resetPotentialTable() { seedPotentialDB = resetSeedTable(seedPotentialDB, seedPotentialDBFile); }
+ private synchronized void resetPassiveTable() { seedPassiveDB = resetSeedTable(seedPassiveDB, seedPassiveDBFile); }
+ private synchronized void resetPotentialTable() { seedPotentialDB = resetSeedTable(seedPotentialDB, seedPotentialDBFile); }
public void close() {
if (seedActiveDB != null) seedActiveDB.close();
@@ -397,12 +398,12 @@ public final class yacySeedDB implements AlternativeDomainNames {
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash, null, seedActiveDB, minVersion);
}
- public Iterator<yacySeed> seedsDisconnected(final boolean up, final boolean rot, final byte[] firstHash, final float minVersion) {
+ private Iterator<yacySeed> seedsDisconnected(final boolean up, final boolean rot, final byte[] firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash, null, seedPassiveDB, minVersion);
}
- public Iterator<yacySeed> seedsPotential(final boolean up, final boolean rot, final byte[] firstHash, final float minVersion) {
+ private Iterator<yacySeed> seedsPotential(final boolean up, final boolean rot, final byte[] firstHash, final float minVersion) {
// enumerates seed-type objects: all seeds sequentially without order
return new seedEnum(up, rot, (firstHash == null) ? null : firstHash, null, seedPotentialDB, minVersion);
}
@@ -451,7 +452,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
}
- public synchronized void addDisconnected(final yacySeed seed) {
+ protected synchronized void addDisconnected(final yacySeed seed) {
if (seed.isProper(false) != null) return;
try {
nameLookupCache.remove(seed.getName());
@@ -470,7 +471,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
}
- public synchronized void addPotential(final yacySeed seed) {
+ protected synchronized void addPotential(final yacySeed seed) {
if (seed.isProper(false) != null) return;
try {
nameLookupCache.remove(seed.getName());
@@ -503,28 +504,16 @@ public final class yacySeedDB implements AlternativeDomainNames {
} catch (final IOException e) { Log.logWarning("yacySeedDB", "could not remove hash ("+ e.getClass() +"): "+ e.getMessage()); }
}
- public boolean hasConnected(final String hash) {
- try {
+ public boolean hasConnected(final byte[] hash) {
return seedActiveDB.has(hash);
- } catch (final IOException e) {
- return false;
- }
}
- public boolean hasDisconnected(final String hash) {
- try {
+ public boolean hasDisconnected(final byte[] hash) {
return seedPassiveDB.has(hash);
- } catch (final IOException e) {
- return false;
- }
}
- public boolean hasPotential(final String hash) {
- try {
+ public boolean hasPotential(final byte[] hash) {
return seedPotentialDB.has(hash);
- } catch (final IOException e) {
- return false;
- }
}
private yacySeed get(final String hash, final MapDataMining database) {
@@ -644,7 +633,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
int pos = -1;
String addressStr = null;
InetAddress seedIPAddress = null;
- final HashSet<String> badPeerHashes = new HashSet<String>();
+ final HandleSet badPeerHashes = new HandleSet(12, Base64Order.enhancedCoder, 0);
if (lookupConnected) {
// enumerate the cache and simultanous insert values
@@ -656,7 +645,12 @@ public final class yacySeedDB implements AlternativeDomainNames {
addressStr = seed.getPublicAddress();
if (addressStr == null) {
Log.logWarning("YACY","lookupByIP/Connected: address of seed " + seed.getName() + "/" + seed.hash + " is null.");
- badPeerHashes.add(seed.hash);
+ try {
+ badPeerHashes.put(seed.hash.getBytes());
+ } catch (RowSpaceExceededException e1) {
+ Log.logException(e1);
+ break;
+ }
continue;
}
if ((pos = addressStr.indexOf(':'))!= -1) {
@@ -669,7 +663,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
} catch (final UnknownHostException ex) {}
}
// delete bad peers
- final Iterator<String> i = badPeerHashes.iterator();
+ final Iterator<byte[]> i = badPeerHashes.iterator();
while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (final IOException e1) {Log.logException(e1);}
badPeerHashes.clear();
}
@@ -685,7 +679,12 @@ public final class yacySeedDB implements AlternativeDomainNames {
addressStr = seed.getPublicAddress();
if (addressStr == null) {
Log.logWarning("YACY","lookupByIPDisconnected: address of seed " + seed.getName() + "/" + seed.hash + " is null.");
- badPeerHashes.add(seed.hash);
+ try {
+ badPeerHashes.put(seed.hash.getBytes());
+ } catch (RowSpaceExceededException e1) {
+ Log.logException(e1);
+ break;
+ }
continue;
}
if ((pos = addressStr.indexOf(':'))!= -1) {
@@ -698,7 +697,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
} catch (final UnknownHostException ex) {}
}
// delete bad peers
- final Iterator<String> i = badPeerHashes.iterator();
+ final Iterator<byte[]> i = badPeerHashes.iterator();
while (i.hasNext()) try {seedActiveDB.remove(i.next());} catch (final IOException e1) {Log.logException(e1);}
badPeerHashes.clear();
}
@@ -739,10 +738,6 @@ public final class yacySeedDB implements AlternativeDomainNames {
return null;
}
}
-
- public ArrayList<String> storeCache(final File seedFile) throws IOException {
- return storeCache(seedFile, false);
- }
private ArrayList<String> storeCache(final File seedFile, final boolean addMySeed) throws IOException {
PrintWriter pw = null;
@@ -778,7 +773,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
return v;
}
- public String uploadCache(final yacySeedUploader uploader,
+ protected String uploadCache(final yacySeedUploader uploader,
final serverSwitch sb,
final yacySeedDB seedDB,
final DigestURI seedURL) throws Exception {
@@ -931,14 +926,14 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
}
- class seedEnum implements Iterator<yacySeed> {
+ private class seedEnum implements Iterator<yacySeed> {
- MapDataMining.mapIterator it;
- yacySeed nextSeed;
- MapDataMining database;
- float minVersion;
+ private MapDataMining.mapIterator it;
+ private yacySeed nextSeed;
+ private MapDataMining database;
+ private float minVersion;
- public seedEnum(final boolean up, final boolean rot, final byte[] firstKey, final byte[] secondKey, final MapDataMining database, final float minVersion) {
+ private seedEnum(final boolean up, final boolean rot, final byte[] firstKey, final byte[] secondKey, final MapDataMining database, final float minVersion) {
this.database = database;
this.minVersion = minVersion;
try {
@@ -963,7 +958,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
}
}
- public seedEnum(final boolean up, final String field, final MapDataMining database) {
+ private seedEnum(final boolean up, final String field, final MapDataMining database) {
this.database = database;
try {
it = database.maps(up, field);
@@ -982,7 +977,7 @@ public final class yacySeedDB implements AlternativeDomainNames {
return (nextSeed != null);
}
- public yacySeed internalNext() {
+ private yacySeed internalNext() {
if ((it == null) || (!(it.hasNext()))) return null;
try {
ConcurrentHashMap<String, String> dna;
diff --git a/source/net/yacy/dbtest.java b/source/net/yacy/dbtest.java
index 9c03c3293..d22e41835 100644
--- a/source/net/yacy/dbtest.java
+++ b/source/net/yacy/dbtest.java
@@ -13,8 +13,8 @@ import java.util.Random;
import javax.imageio.ImageIO;
-import net.yacy.kelondro.index.ObjectArrayCache;
import net.yacy.kelondro.index.ObjectIndex;
+import net.yacy.kelondro.index.ObjectIndexCache;
import net.yacy.kelondro.index.Row;
import net.yacy.kelondro.index.RowSet;
import net.yacy.kelondro.index.RowSpaceExceededException;
@@ -408,93 +408,6 @@ public class dbtest {
}
}
- if (command.equals("stressThreaded")) {
- //
- // args: <number-of-writes> <number-of-reads-per-write> <random-startpoint>
- // example: java -ea -classpath classes dbtest stressThreaded kelondroEcoTable kelondroFlexTable stressthreadedtest 500 50 0
- /* result with svn 4346
- kelondroFlex:
- removed: 70, size of jcontrol set: 354, size of kcontrol set: 354
- Database size = 354 unique entries.
- Execution time: open=1329, command=36234, close=17, total=37580
- kelondroEco:
- removed: 70, size of jcontrol set: 354, size of kcontrol set: 354
- Database size = 354 unique entries.
- Execution time: open=1324, command=34032, close=1, total=35357
- */
- final long writeCount = Long.parseLong(args[4]);
- final long readCount = Long.parseLong(args[5]);
- final long randomstart = Long.parseLong(args[6]);
- final Random random = new Random(randomstart);
- long r;
- Long R;
- int p, rc=0;
- final ArrayList<Long> ra = new ArrayList<Long>();
- final HashSet<Long> jcontrol = new HashSet<Long>();
- final ObjectArrayCache kcontrol = new ObjectArrayCache(1, 0);
- for (int i = 0; i < writeCount; i++) {
- r = Math.abs(random.nextLong() % 1000);
- jcontrol.add(Long.valueOf(r));
- kcontrol.putb((int) r, "x".getBytes());
- InstantBusyThread.oneTimeJob(new WriteJob(table_test, table_reference, r), 0, 50);
- if (random.nextLong() % 5 == 0) ra.add(Long.valueOf(r));
- for (int j = 0; j < readCount; j++) {
- InstantBusyThread.oneTimeJob(new ReadJob(table_test, table_reference, random.nextLong() % writeCount), random.nextLong() % 1000, 20);
- }
- if (!ra.isEmpty() && random.nextLong() % 7 == 0) {
- rc++;
- p = Math.abs(random.nextInt() % ra.size());
- R = ra.get(p);
- jcontrol.remove(R);
- kcontrol.removeb((int) R.longValue());
- System.out.println("remove: " + R.longValue());
- InstantBusyThread.oneTimeJob(new RemoveJob(table_test, table_reference, (ra.remove(p)).longValue()), 0, 50);
- }
- }
- System.out.println("removed: " + rc + ", size of jcontrol set: " + jcontrol.size() + ", size of kcontrol set: " + kcontrol.size());
- while (InstantBusyThread.instantThreadCounter > 0) {
- try {Thread.sleep(1000);} catch (final InterruptedException e) {} // wait for all tasks to finish
- System.out.println("count: " + InstantBusyThread.instantThreadCounter + ", jobs: " + InstantBusyThread.jobs.toString());
- }
- try {Thread.sleep(6000);} catch (final InterruptedException e) {}
- }
-
- if (command.equals("stressSequential")) {
- //
- // args: <number-of-writes> <number-of-reads> <random-startpoint>
- final long writeCount = Long.parseLong(args[4]);
- final long readCount = Long.parseLong(args[5]);
- final long randomstart = Long.parseLong(args[6]);
- final Random random = new Random(randomstart);
- long r;
- Long R;
- int p, rc=0;
- final ArrayList<Long> ra = new ArrayList<Long>();
- final HashSet<Long> jcontrol = new HashSet<Long>();
- final ObjectArrayCache kcontrol = new ObjectArrayCache(1, 0);
- for (int i = 0; i < writeCount; i++) {
- //if (i == 30) random = new Random(randomstart);
- r = Math.abs(random.nextLong() % 1000);
- jcontrol.add(Long.valueOf(r));
- kcontrol.putb((int) r, "x".getBytes());
- new WriteJob(table_test, table_reference, r).run();
- if (random.nextLong() % 5 == 0) ra.add(Long.valueOf(r));
- for (int j = 0; j < readCount; j++) {
- new ReadJob(table_test, table_reference, random.nextLong() % writeCount).run();
- }
- if (!ra.isEmpty() && random.nextLong() % 7 == 0) {
- rc++;
- p = Math.abs(random.nextInt() % ra.size());
- R = ra.get(p);
- jcontrol.remove(R);
- kcontrol.removeb((int) R.longValue());
- new RemoveJob(table_test, table_reference, (ra.remove(p)).longValue()).run();
- }
- }
- try {Thread.sleep(1000);} catch (final InterruptedException e) {}
- System.out.println("removed: " + rc + ", size of jcontrol set: " + jcontrol.size() + ", size of kcontrol set: " + kcontrol.size());
- }
-
final long aftercommand = System.currentTimeMillis();
checkEquivalence(table_test, table_reference);
final long afterequiv = System.currentTimeMillis();
diff --git a/source/net/yacy/kelondro/blob/Compressor.java b/source/net/yacy/kelondro/blob/Compressor.java
index 925f5c60d..eb1fe96b2 100644
--- a/source/net/yacy/kelondro/blob/Compressor.java
+++ b/source/net/yacy/kelondro/blob/Compressor.java
@@ -348,7 +348,6 @@ public class Compressor implements BLOB {
while (!this.buffer.isEmpty()) {
if (!flushOne()) break;
}
- assert this.bufferlength == 0;
}
public int replace(byte[] key, Rewriter rewriter) throws IOException {
diff --git a/source/net/yacy/kelondro/blob/HeapReader.java b/source/net/yacy/kelondro/blob/HeapReader.java
index 970137dfe..79ca2b58b 100644
--- a/source/net/yacy/kelondro/blob/HeapReader.java
+++ b/source/net/yacy/kelondro/blob/HeapReader.java
@@ -154,7 +154,7 @@ public class HeapReader {
// there is an index and a gap file:
// read the index file:
try {
- this.index = new HandleMap(this.keylength, this.ordering, 8, fif, 1000000);
+ this.index = new HandleMap(this.keylength, this.ordering, 8, fif);
} catch (IOException e) {
Log.logException(e);
return false;
@@ -237,7 +237,7 @@ public class HeapReader {
// new seek position
seek += 4L + reclen;
}
- indexready.finish(true);
+ indexready.finish();
// finish the index generation
try {
@@ -561,7 +561,7 @@ public class HeapReader {
public entries(final File blobFile, final int keylen) throws IOException {
if (!(blobFile.exists())) throw new IOException("file " + blobFile + " does not exist");
- this.is = new DataInputStream(new BufferedInputStream(new FileInputStream(blobFile), 4*1024*1024));
+ this.is = new DataInputStream(new BufferedInputStream(new FileInputStream(blobFile), 8*1024*1024));
this.keylen = keylen;
this.blobFile = blobFile;
this.nextEntry = next0();
diff --git a/source/net/yacy/kelondro/blob/HeapWriter.java b/source/net/yacy/kelondro/blob/HeapWriter.java
index 1f9f90af8..8555fb3ae 100644
--- a/source/net/yacy/kelondro/blob/HeapWriter.java
+++ b/source/net/yacy/kelondro/blob/HeapWriter.java
@@ -82,7 +82,6 @@ public final class HeapWriter {
this.keylength = keylength;
this.index = new HandleMap(keylength, ordering, 8, 100000);
this.os = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(temporaryHeapFile), outBuffer));
- //this.doublecheck = new HashSet<String>();
this.seek = 0;
}
diff --git a/source/net/yacy/kelondro/blob/MapHeap.java b/source/net/yacy/kelondro/blob/MapHeap.java
index 136ab3a57..983a17a59 100644
--- a/source/net/yacy/kelondro/blob/MapHeap.java
+++ b/source/net/yacy/kelondro/blob/MapHeap.java
@@ -67,28 +67,6 @@ public class MapHeap {
this.blob = new Heap(heapFile, keylength, ordering, buffermax);
this.cache = new ConcurrentARC<String, Map<String, String>>(cachesize, Runtime.getRuntime().availableProcessors());
this.fillchar = fillchar;
- /*
- // debug
- try {
- kelondroCloneableIterator<byte[]> i = keys(true, false);
- int c = 20;
- HashSet<String> t = new HashSet<String>();
- while (i.hasNext()) {
- c--; if (c <= 0) break;
- byte[] b = i.next();
- String s = new String(b);
- System.out.println("*** DEBUG kelondroMap " + blob.name() + " KEY=" + s);
- t.add(s);
- }
- Iterator<String> j = t.iterator();
- while (j.hasNext()) {
- String s = j.next();
- if (this.get(s) == null) System.out.println("*** DEBUG kelondroMap " + blob.name() + " KEY=" + s + " cannot be found.");
- }
- } catch (IOException e) {
- Log.logException(e);
- }
- */
}
/**
@@ -155,10 +133,10 @@ public class MapHeap {
assert key.length() > 0;
assert newMap != null;
key = normalizeKey(key);
- byte[] keyb = key.getBytes("UTF-8");
+ byte[] keyb = key.getBytes();
String s = map2string(newMap, "W" + DateFormatter.formatShortSecond() + " ");
assert s != null;
- byte[] sb = s.getBytes("UTF-8");
+ byte[] sb = s.getBytes();
synchronized (this) {
// write entry
if (blob != null) blob.put(keyb, sb);
@@ -180,7 +158,7 @@ public class MapHeap {
synchronized (this) {
// remove from cache
- cache.remove(new String(key, "UTF-8"));
+ cache.remove(new String(key));
// remove from file
blob.remove(key);
@@ -196,7 +174,7 @@ public class MapHeap {
// update elementCount
if (key == null) return;
key = normalizeKey(key);
- byte[] keyb = key.getBytes("UTF-8");
+ byte[] keyb = key.getBytes();
synchronized (this) {
// remove from cache
@@ -217,13 +195,24 @@ public class MapHeap {
assert key != null;
if (cache == null) return false; // case may appear during shutdown
key = normalizeKey(key);
- byte[] keyb = key.getBytes("UTF-8");
+ byte[] keyb = key.getBytes();
boolean h;
synchronized (this) {
h = this.cache.containsKey(key) || this.blob.has(keyb);
}
return h;
}
+
+ public boolean has(byte[] key) {
+ assert key != null;
+ if (cache == null) return false; // case may appear during shutdown
+ key = normalizeKey(key);
+ boolean h;
+ synchronized (this) {
+ h = this.cache.containsKey(new String(key)) || this.blob.has(key);
+ }
+ return h;
+ }
/**
* retrieve the whole Map from the table
@@ -264,7 +253,7 @@ public class MapHeap {
assert key != null;
if (cache == null) return null; // case may appear during shutdown
key = normalizeKey(key);
- byte[] keyb = key.getBytes("UTF-8");
+ byte[] keyb = key.getBytes();
Map<String, String> map;
if (storeCache) {
@@ -393,7 +382,7 @@ public class MapHeap {
return null;
}
try {
- final Map<String, String> obj = get(new String(nextKey, "UTF-8"));
+ final Map<String, String> obj = get(new String(nextKey));
if (obj == null) throw new kelondroException("no more elements available");
return obj;
} catch (final IOException e) {
@@ -422,7 +411,7 @@ public class MapHeap {
// iterate over keys
Iterator<byte[]> i = map.keys(true, false);
while (i.hasNext()) {
- System.out.println("key: " + new String(i.next(), "UTF-8"));
+ System.out.println("key: " + new String(i.next()));
}
// clean up
map.close();
diff --git a/source/net/yacy/kelondro/index/BinSearch.java b/source/net/yacy/kelondro/index/BinSearch.java
index b56772764..af5ebb5ed 100644
--- a/source/net/yacy/kelondro/index/BinSearch.java
+++ b/source/net/yacy/kelondro/index/BinSearch.java
@@ -54,7 +54,8 @@ public final class BinSearch {
if (beginPos >= endPos) return false;
final int pivot = (beginPos + endPos) / 2;
if ((pivot < 0) || (pivot >= this.count)) return false;
- final int c = objectOrder.compare(this.chunks, pivot * this.chunksize, this.chunksize, t, 0, t.length);
+ assert this.chunksize == t.length;
+ final int c = objectOrder.compare(this.chunks, pivot * this.chunksize, t, 0, this.chunksize);
if (c == 0) return true;
if (c < 0) /* buffer < t */ return contains(t, pivot + 1, endPos);
if (c > 0) /* buffer > t */ return contains(t, beginPos, pivot);
diff --git a/source/net/yacy/kelondro/index/BufferedObjectIndex.java b/source/net/yacy/kelondro/index/BufferedObjectIndex.java
index 02dea9826..5833aad6d 100644
--- a/source/net/yacy/kelondro/index/BufferedObjectIndex.java
+++ b/source/net/yacy/kelondro/index/BufferedObjectIndex.java
@@ -50,6 +50,18 @@ public class BufferedObjectIndex implements ObjectIndex, Iterable<Row.Entry> {
this.entryComparator = new Row.EntryComparator(backend.row().objectOrder);
}
+ public byte[] smallestKey() {
+ if (this.buffer == null || this.buffer.isEmpty()) return this.backend.smallestKey();
+ if (this.backend.isEmpty()) return this.buffer.smallestKey();
+ return this.backend.row().getOrdering().smallest(this.buffer.smallestKey(), this.backend.smallestKey());
+ }
+
+ public byte[] largestKey() {
+ if (this.buffer == null || this.buffer.isEmpty()) return this.backend.largestKey();
+ if (this.backend.isEmpty()) return this.buffer.largestKey();
+ return this.backend.row().getOrdering().largest(this.buffer.largestKey(), this.backend.largestKey());
+ }
+
private final void flushBuffer() throws IOException, RowSpaceExceededException {
if (this.buffer.size() > 0) {
for (Row.Entry e: this.buffer) {
diff --git a/source/net/yacy/kelondro/index/Cache.java b/source/net/yacy/kelondro/index/Cache.java
index 6813f64ef..cb179f901 100644
--- a/source/net/yacy/kelondro/index/Cache.java
+++ b/source/net/yacy/kelondro/index/Cache.java
@@ -79,7 +79,7 @@ public final class Cache implements ObjectIndex, Iterable<Row.Entry> {
init();
objectTracker.put(backupIndex.filename(), this);
}
-
+
private void init() {
Row row = index.row();
this.keyrow = new Row(new Column[]{row.column(0)}, row.objectOrder);
@@ -118,6 +118,14 @@ public final class Cache implements ObjectIndex, Iterable<Row.Entry> {
return this.missLimit;
}
+ public byte[] smallestKey() {
+ return this.index.smallestKey();
+ }
+
+ public byte[] largestKey() {
+ return this.index.largestKey();
+ }
+
public static final Iterator<String> filenames() {
// iterates string objects; all file names from record tracker
return objectTracker.keySet().iterator();
diff --git a/source/net/yacy/kelondro/index/HandleMap.java b/source/net/yacy/kelondro/index/HandleMap.java
index b17f8720b..520a4478a 100644
--- a/source/net/yacy/kelondro/index/HandleMap.java
+++ b/source/net/yacy/kelondro/index/HandleMap.java
@@ -52,7 +52,7 @@ import net.yacy.kelondro.order.CloneableIterator;
public final class HandleMap implements Iterable<Row.Entry> {
private final Row rowdef;
- protected ObjectIndexCache index;
+ private RowSetArray index;
/**
* initialize a HandleMap
@@ -64,12 +64,7 @@ public final class HandleMap implements Iterable<Row.Entry> {
*/
public HandleMap(final int keylength, final ByteOrder objectOrder, final int idxbytes, final int expectedspace) {
this.rowdef = new Row(new Column[]{new Column("key", Column.celltype_binary, Column.encoder_bytes, keylength, "key"), new Column("long c-" + idxbytes + " {b256}")}, objectOrder);
- this.index = new ObjectIndexCache(rowdef, expectedspace);
- }
-
- public HandleMap(final int keylength, final ByteOrder objectOrder, final int idxbytes, final int expectedspace, final int initialspace) throws RowSpaceExceededException {
- this.rowdef = new Row(new Column[]{new Column("key", Column.celltype_binary, Column.encoder_bytes, keylength, "key"), new Column("long c-" + idxbytes + " {b256}")}, objectOrder);
- this.index = new ObjectIndexCache(rowdef, expectedspace, initialspace);
+ this.index = new RowSetArray(rowdef, spread(expectedspace));
}
/**
@@ -80,8 +75,8 @@ public final class HandleMap implements Iterable<Row.Entry> {
* @throws IOException
* @throws RowSpaceExceededException
*/
- public HandleMap(final int keylength, final ByteOrder objectOrder, final int idxbytes, final File file, final int expectedspace) throws IOException, RowSpaceExceededException {
- this(keylength, objectOrder, idxbytes, expectedspace, (int) (file.length() / (keylength + idxbytes)));
+ public HandleMap(final int keylength, final ByteOrder objectOrder, final int idxbytes, final File file) throws IOException, RowSpaceExceededException {
+ this(keylength, objectOrder, idxbytes, (int) (file.length() / (keylength + idxbytes)));
// read the index dump and fill the index
InputStream is = new BufferedInputStream(new FileInputStream(file), 1024 * 1024);
if (file.getName().endsWith(".gz")) is = new GZIPInputStream(is);
@@ -99,6 +94,10 @@ public final class HandleMap implements Iterable<Row.Entry> {
assert this.index.size() == file.length() / (keylength + idxbytes);
}
+ private static final int spread(int expectedspace) {
+ return Math.min(Runtime.getRuntime().availableProcessors() * 2, Math.max(1, expectedspace / 3000));
+ }
+
public final int[] saturation() {
int keym = 0;
int valm = this.rowdef.width(1);
@@ -319,12 +318,10 @@ public final class HandleMap implements Iterable<Row.Entry> {
private final BlockingQueue<entry> cache;
private final HandleMap map;
private Future<HandleMap> result;
- private boolean sortAtEnd;
public initDataConsumer(final HandleMap map) {
this.map = map;
cache = new LinkedBlockingQueue<entry>();
- sortAtEnd = false;
}
protected final void setResult(final Future<HandleMap> result) {
@@ -348,8 +345,7 @@ public final class HandleMap implements Iterable<Row.Entry> {
* to signal the initialization thread that no more entries will be submitted with consumer()
* this method must be called. The process will not terminate if this is not called before.
*/
- public final void finish(final boolean sortAtEnd) {
- this.sortAtEnd = sortAtEnd;
+ public final void finish() {
try {
cache.put(poisonEntry);
} catch (InterruptedException e) {
@@ -380,9 +376,6 @@ public final class HandleMap implements Iterable<Row.Entry> {
} catch (RowSpaceExceededException e) {
Log.logException(e);
}
- if (sortAtEnd) {
- map.index.finishInitialization();
- }
return map;
}
diff --git a/source/net/yacy/kelondro/index/HandleSet.java b/source/net/yacy/kelondro/index/HandleSet.java
index 40d8c7898..f3fc9e369 100644
--- a/source/net/yacy/kelondro/index/HandleSet.java
+++ b/source/net/yacy/kelondro/index/HandleSet.java
@@ -43,25 +43,29 @@ import net.yacy.kelondro.util.SetTools;
public final class HandleSet implements Iterable<byte[]>, Cloneable {
private final Row rowdef;
- private ObjectIndex index;
+ private RowSet index;
public HandleSet(final int keylength, final ByteOrder objectOrder, final int expectedspace) {
this.rowdef = new Row(new Column[]{new Column("key", Column.celltype_binary, Column.encoder_bytes, keylength, "key")}, objectOrder);
- this.index = new ObjectIndexCache(rowdef, expectedspace);
- }
-
- public HandleSet(final int keylength, final ByteOrder objectOrder, final int expectedspace, final int initialspace) throws RowSpaceExceededException {
- this.rowdef = new Row(new Column[]{new Column("key", Column.celltype_binary, Column.encoder_bytes, keylength, "key")}, objectOrder);
- this.index = new ObjectIndexCache(rowdef, expectedspace, initialspace);
+ try {
+ this.index = new RowSet(rowdef, expectedspace);
+ } catch (RowSpaceExceededException e) {
+ try {
+ this.index = new RowSet(rowdef, 0);
+ } catch (RowSpaceExceededException ee) {
+ Log.logException(ee);
+ this.index = null;
+ }
+ }
}
- private HandleSet(Row rowdef, ObjectIndex index) {
+ private HandleSet(Row rowdef, RowSet index) {
this.rowdef = rowdef;
this.index = index;
}
public HandleSet clone() {
- return new HandleSet(this.rowdef, ((ObjectIndexCache) this.index).clone());
+ return new HandleSet(this.rowdef, this.index.clone());
}
/**
@@ -72,8 +76,8 @@ public final class HandleSet implements Iterable<byte[]>, Cloneable {
* @throws IOException
* @throws RowSpaceExceededException
*/
- public HandleSet(final int keylength, final ByteOrder objectOrder, final File file, final int expectedspace) throws IOException, RowSpaceExceededException {
- this(keylength, objectOrder, expectedspace, (int) (file.length() / (keylength + 8)));
+ public HandleSet(final int keylength, final ByteOrder objectOrder, final File file) throws IOException, RowSpaceExceededException {
+ this(keylength, objectOrder, (int) (file.length() / (keylength + 8)));
// read the index dump and fill the index
final InputStream is = new BufferedInputStream(new FileInputStream(file), 1024 * 1024);
final byte[] a = new byte[keylength];
@@ -110,6 +114,14 @@ public final class HandleSet implements Iterable<byte[]>, Cloneable {
return c;
}
+ public final synchronized byte[] smallestKey() {
+ return this.index.smallestKey();
+ }
+
+ public final synchronized byte[] largestKey() {
+ return this.index.largestKey();
+ }
+
public ByteOrder comparator() {
return this.rowdef.objectOrder;
}
@@ -119,11 +131,7 @@ public final class HandleSet implements Iterable<byte[]>, Cloneable {
}
public final void clear() {
- try {
- this.index.clear();
- } catch (IOException e) {
- Log.logException(e);
- }
+ this.index.clear();
}
public final synchronized boolean has(final byte[] key) {
@@ -139,46 +147,28 @@ public final class HandleSet implements Iterable<byte[]>, Cloneable {
assert (key != null);
final Row.Entry newentry = index.row().newEntry();
newentry.setCol(0, key);
- try {
- index.put(newentry);
- } catch (IOException e) {
- Log.logException(e);
- }
+ index.put(newentry);
}
public final synchronized void putUnique(final byte[] key) throws RowSpaceExceededException {
assert (key != null);
final Row.Entry newentry = this.rowdef.newEntry();
newentry.setCol(0, key);
- try {
- index.addUnique(newentry);
- } catch (IOException e) {
- Log.logException(e);
- }
+ index.addUnique(newentry);
}
public final synchronized boolean remove(final byte[] key) {
assert (key != null);
Row.Entry indexentry;
- try {
- indexentry = index.remove(key);
- return indexentry != null;
- } catch (IOException e) {
- Log.logException(e);
- return false;
- }
+ indexentry = index.remove(key);
+ return indexentry != null;
}
public final synchronized byte[] removeone() {
Row.Entry indexentry;
- try {
- indexentry = index.removeOne();
- if (indexentry == null) return null;
- return indexentry.getColBytes(0, true);
- } catch (IOException e) {
- Log.logException(e);
- return null;
- }
+ indexentry = index.removeOne();
+ if (indexentry == null) return null;
+ return indexentry.getColBytes(0, true);
}
public final synchronized boolean isEmpty() {
@@ -190,12 +180,7 @@ public final class HandleSet implements Iterable<byte[]>, Cloneable {
}
public final synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) {
- try {
- return index.keys(up, firstKey);
- } catch (IOException e) {
- Log.logException(e);
- return null;
- }
+ return index.keys(up, firstKey);
}
public final Iterator<byte[]> iterator() {
diff --git a/source/net/yacy/kelondro/index/IndexTest.java b/source/net/yacy/kelondro/index/IndexTest.java
index 7fd651389..b79e5e1a7 100644
--- a/source/net/yacy/kelondro/index/IndexTest.java
+++ b/source/net/yacy/kelondro/index/IndexTest.java
@@ -113,11 +113,7 @@ public class IndexTest {
Runtime.getRuntime().gc();
final long freeStartKelondro = MemoryControl.available();
HandleMap ii = null;
- try {
- ii = new HandleMap(12, Base64Order.enhancedCoder, 4, count, count);
- } catch (RowSpaceExceededException e1) {
- e1.printStackTrace();
- }
+ ii = new HandleMap(12, Base64Order.enhancedCoder, 4, count);
for (int i = 0; i < count; i++)
try {
ii.putUnique(tests[i], 1);
diff --git a/source/net/yacy/kelondro/index/ObjectArray.java b/source/net/yacy/kelondro/index/ObjectArray.java
deleted file mode 100644
index 5dc054247..000000000
--- a/source/net/yacy/kelondro/index/ObjectArray.java
+++ /dev/null
@@ -1,46 +0,0 @@
-// ObjectArray.java
-// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 01.06.2006 on http://www.anomic.de
-//
-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
-// $LastChangedRevision: 1986 $
-// $LastChangedBy: orbiter $
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.kelondro.index;
-
-import java.io.IOException;
-
-
-public interface ObjectArray {
-
- public int size();
-
- public Row row();
-
- public void set(int index, Row.Entry rowentry) throws IOException;
-
- public Row.Entry get(int index) throws IOException;
-
- public int add(Row.Entry rowinstance) throws IOException;
-
- public void remove(int index) throws IOException;
-
- public void print() throws IOException;
-
-}
diff --git a/source/net/yacy/kelondro/index/ObjectArrayCache.java b/source/net/yacy/kelondro/index/ObjectArrayCache.java
deleted file mode 100644
index b23775bdc..000000000
--- a/source/net/yacy/kelondro/index/ObjectArrayCache.java
+++ /dev/null
@@ -1,256 +0,0 @@
-// ObjectArrayCache.java
-// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 08.06.2006 on http://www.anomic.de
-//
-// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
-// $LastChangedRevision: 1986 $
-// $LastChangedBy: orbiter $
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.kelondro.index;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Random;
-
-import net.yacy.kelondro.order.NaturalOrder;
-
-
-public final class ObjectArrayCache {
-
- // we use two indexes: one for initialization, and one for data acquired during runtime
- // this has a gread advantage, if the setup-data is large. Then a re-organization of
- // the run-time data does not need much memory and is done faster.
- // we distinguish two phases: the init phase where data can only be written
- // to index0 with addb, and a runtime-phase where data can only be written
- // to index1 with putb.
-
- private final Row rowdef;
- private final RowSet index0;
- private RowSet index1;
- //private final kelondroOrder<kelondroRow.Entry> entryOrder;
-
- public ObjectArrayCache(final int payloadSize) {
- this.rowdef = new Row("Cardinal key-4 {b256}, byte[] payload-" + payloadSize, NaturalOrder.naturalOrder);
- this.index0 = new RowSet(rowdef);
- this.index1 = null;
- }
-
- public ObjectArrayCache(final int payloadSize, final int initSize) throws RowSpaceExceededException {
- this.rowdef = new Row("Cardinal key-4 {b256}, byte[] payload-" + payloadSize, NaturalOrder.naturalOrder);
- this.index0 = new RowSet(rowdef, initSize);
- this.index1 = null;
- }
-
- public final long memoryNeededForGrow() {
- if (index1 == null)
- return index0.memoryNeededForGrow();
- return index1.memoryNeededForGrow();
- }
-
- public final Row row() {
- return index0.row();
- }
-
- public final byte[] getb(final int ii) {
- assert ii >= 0 : "i = " + ii;
- final byte[] key = NaturalOrder.encodeLong(ii, 4);
- if (index0 != null) {
- if (index1 == null) {
- // finish initialization phase
- index0.sort();
- index0.uniq();
- index1 = new RowSet(rowdef);
- }
- final Row.Entry indexentry = index0.get(key);
- if (indexentry != null) return indexentry.getColBytes(1, false);
- }
- assert (index1 != null);
- final Row.Entry indexentry = index1.get(key);
- if (indexentry == null) return null;
- return indexentry.getColBytes(1, false);
- }
-
- public final byte[] putb(final int ii, final byte[] value) throws RowSpaceExceededException {
- assert ii >= 0 : "i = " + ii;
- assert value != null;
- final byte[] key = NaturalOrder.encodeLong(ii, 4);
- if (index0 != null) {
- if (index1 == null) {
- // finish initialization phase
- index0.sort();
- index0.uniq();
- index1 = new RowSet(rowdef, 0);
- }
- final Row.Entry indexentry = index0.get(key);
- if (indexentry != null) {
- final byte[] oldv = indexentry.getColBytes(1, false);
- indexentry.setCol(0, key);
- indexentry.setCol(1, value);
- index0.put(indexentry);
- return oldv;
- }
- // else place it in the index1
- }
- // at this point index1 cannot be null
- assert (index1 != null);
-
- final Row.Entry newentry = rowdef.newEntry();
- newentry.setCol(0, ii);
- newentry.setCol(1, value);
- final Row.Entry oldentry = index1.replace(newentry);
- if (oldentry == null) return null;
- return oldentry.getColBytes(1, false);
- }
-
- public final void addb(final int ii, final byte[] value) throws RowSpaceExceededException {
- assert index1 == null; // valid only in init-phase
- assert ii >= 0 : "i = " + ii;
- assert value != null;
- final Row.Entry newentry = index0.row().newEntry();
- newentry.setCol(0, ii);
- newentry.setCol(1, value);
- index0.addUnique(newentry);
- }
-
- public final byte[] removeb(final int ii) {
- assert ii >= 0 : "i = " + ii;
-
- final byte[] key = NaturalOrder.encodeLong(ii, 4);
- if (index0 != null) {
- if (index1 == null) {
- // finish initialization phase
- index0.sort();
- index0.uniq();
- index1 = new RowSet(rowdef);
- }
- final Row.Entry indexentry = index0.remove(key);
- if (indexentry != null) {
- return indexentry.getColBytes(1, false);
- }
- // else remove it from the index1
- }
- // at this point index1 cannot be null
- assert (index1 != null);
- if (index1.isEmpty()) return null;
- final Row.Entry indexentry = index1.remove(key);
- if (indexentry == null) return null;
- return indexentry.getColBytes(1, false);
- }
-
- public final byte[] removeoneb() {
- if (index1 != null && !index1.isEmpty()) {
- final Row.Entry indexentry = index1.removeOne();
- assert (indexentry != null);
- if (indexentry == null) return null;
- //assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
- return indexentry.getColBytes(1, false);
- }
- if (index0 != null && !index0.isEmpty()) {
- final Row.Entry indexentry = index0.removeOne();
- assert (indexentry != null);
- if (indexentry == null) return null;
- //assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
- return indexentry.getColBytes(1, false);
- }
- return null;
- }
-
- public final int size() {
- if ((index0 != null) && (index1 == null)) {
- //assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
- return index0.size();
- }
- if ((index0 == null) && (index1 != null)) {
- //assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
- return index1.size();
- }
- assert ((index0 != null) && (index1 != null));
- //assert consistencyAnalysis0() : "consistency problem: " + consistencyAnalysis();
- return index0.size() + index1.size();
- }
-
- public final Iterator<Row.Entry> rows() {
- if (index0 != null) {
- if (index1 == null) {
- // finish initialization phase
- index0.sort();
- index0.uniq();
- index1 = new RowSet(rowdef);
- }
- return index0.rows();
- } else {
- assert (index1 != null);
- return index1.rows();
- }
- }
-
- public final void flush() {
- if (index0 != null) {
- index0.sort();
- index0.trim(true);
- }
- if (index1 != null) {
- index1.sort();
- index1.trim(true);
- }
- }
-
- public static void main(final String[] args) {
- boolean assertEnabled = false;
- assert assertEnabled = true;
- System.out.println((assertEnabled) ? "asserts are enabled" : "enable asserts with 'java -ea'; not enabled yet");
- final long start = System.currentTimeMillis();
- final long randomstart = 0;
- final Random random = new Random(randomstart);
- long r;
- Long R;
- int p, rc = 0;
- final ArrayList<Long> ra = new ArrayList<Long>();
- final HashSet<Long> jcontrol = new HashSet<Long>();
- final ObjectArrayCache kcontrol = new ObjectArrayCache(1);
- for (int i = 0; i < 1000000; i++) {
- r = Math.abs(random.nextLong() % 10000);
- //System.out.println("add " + r);
- jcontrol.add(Long.valueOf(r));
- try {
- kcontrol.putb((int) r, "x".getBytes());
- } catch (RowSpaceExceededException e) {
- e.printStackTrace();
- }
- if (random.nextLong() % 5 == 0) ra.add(Long.valueOf(r));
- if (!ra.isEmpty() && random.nextLong() % 7 == 0) {
- rc++;
- p = Math.abs(random.nextInt() % ra.size());
- R = ra.get(p);
- //System.out.println("remove " + R.longValue());
- jcontrol.remove(R);
- kcontrol.removeb((int) R.longValue());
- assert kcontrol.removeb((int) R.longValue()) == null;
- }
- assert jcontrol.size() == kcontrol.size();
- }
- System.out.println("removed: " + rc + ", size of jcontrol set: "
- + jcontrol.size() + ", size of kcontrol set: "
- + kcontrol.size());
- System.out.println("Time: "
- + ((System.currentTimeMillis() - start) / 1000) + " seconds");
- }
-
-}
diff --git a/source/net/yacy/kelondro/index/ObjectIndex.java b/source/net/yacy/kelondro/index/ObjectIndex.java
index 6de591b3b..7daa42431 100644
--- a/source/net/yacy/kelondro/index/ObjectIndex.java
+++ b/source/net/yacy/kelondro/index/ObjectIndex.java
@@ -44,6 +44,8 @@ public interface ObjectIndex extends Iterable<Row.Entry> {
public int size();
public boolean isEmpty();
public Row row();
+ public byte[] smallestKey();
+ public byte[] largestKey();
public boolean has(byte[] key); // use this only if there is no get in case that has returns true
public Row.Entry get(byte[] key) throws IOException;
public Row.Entry replace(Row.Entry row) throws RowSpaceExceededException, IOException;
diff --git a/source/net/yacy/kelondro/index/Row.java b/source/net/yacy/kelondro/index/Row.java
index a9d317686..a3fd651b6 100644
--- a/source/net/yacy/kelondro/index/Row.java
+++ b/source/net/yacy/kelondro/index/Row.java
@@ -329,7 +329,8 @@ public final class Row {
public final int compareTo(final Entry o) {
// compares only the content of the primary key
if (objectOrder == null) throw new kelondroException("objects cannot be compared, no order given");
- return objectOrder.compare(this.bytes(), 0, this.getPrimaryKeyLength(), o.bytes(), 0, o.getPrimaryKeyLength());
+ assert primaryKeyLength == o.getPrimaryKeyLength();
+ return objectOrder.compare(this.bytes(), 0, o.bytes(), 0, primaryKeyLength);
}
public int compare(final Entry o1, final Entry o2) {
@@ -696,7 +697,8 @@ public final class Row {
public Entry get(final byte[] key) {
for (Entry e: this.queue) {
- if (objectOrder.compare(key, 0, key.length, e.bytes(), 0, e.getPrimaryKeyLength()) == 0) {
+ assert key.length == e.getPrimaryKeyLength();
+ if (objectOrder.compare(key, 0, e.bytes(), 0, key.length) == 0) {
return e;
}
}
@@ -708,7 +710,8 @@ public final class Row {
Entry e;
while (i.hasNext()) {
e = i.next();
- if (objectOrder.compare(key, 0, key.length, e.bytes(), 0, e.getPrimaryKeyLength()) == 0) {
+ assert key.length == e.getPrimaryKeyLength();
+ if (objectOrder.compare(key, 0, e.bytes(), 0, key.length) == 0) {
i.remove();
return e;
}
diff --git a/source/net/yacy/kelondro/index/RowCollection.java b/source/net/yacy/kelondro/index/RowCollection.java
index 294790f31..20370095e 100644
--- a/source/net/yacy/kelondro/index/RowCollection.java
+++ b/source/net/yacy/kelondro/index/RowCollection.java
@@ -162,6 +162,8 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
private static Column exportColumn0, exportColumn1, exportColumn2, exportColumn3, exportColumn4;
+ protected static final int exportOverheadSize = 14;
+
private static Row exportRow(final int chunkcachelength) {
/*
return new Row(
@@ -184,16 +186,16 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
* because of a strange bug these objects cannot be initialized as normal
* static final. If I try that, they are not initialized and are assigned null. why?
*/
- return new Row(new Column[]{
+ Row er = new Row(new Column[]{
exportColumn0, exportColumn1, exportColumn2, exportColumn3, exportColumn4,
new Column("byte[] collection-" + chunkcachelength)
},
NaturalOrder.naturalOrder
);
+ assert er.objectsize == chunkcachelength +exportOverheadSize;
+ return er;
}
- protected static final int exportOverheadSize = 14;
-
public synchronized byte[] exportCollection() {
// returns null if the collection is empty
trim(false);
@@ -373,7 +375,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
this.sortBound = 1;
} else if (
this.sortBound + 1 == chunkcount &&
- this.rowdef.objectOrder.compare(chunkcache, rowdef.objectsize * (chunkcount - 2), rowdef.primaryKeyLength,
+ this.rowdef.objectOrder.compare(chunkcache, rowdef.objectsize * (chunkcount - 2),
chunkcache, rowdef.objectsize * (chunkcount - 1), rowdef.primaryKeyLength) == -1) {
this.sortBound = chunkcount;
}
@@ -455,7 +457,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
return r;
}
- protected synchronized byte[] smallestKey() {
+ public synchronized byte[] smallestKey() {
if (chunkcount == 0) return null;
this.sort();
final Row.Entry r = get(0, false);
@@ -463,7 +465,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
return b;
}
- protected synchronized byte[] largestKey() {
+ public synchronized byte[] largestKey() {
if (chunkcount == 0) return null;
this.sort();
final Row.Entry r = get(chunkcount - 1, false);
@@ -929,7 +931,6 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
final int c = this.rowdef.objectOrder.compare(
chunkcache,
i * this.rowdef.objectsize,
- this.rowdef.primaryKeyLength,
chunkcache,
j * this.rowdef.objectsize,
this.rowdef.primaryKeyLength);
@@ -939,7 +940,7 @@ public class RowCollection implements Iterable<Row.Entry>, Cloneable {
protected synchronized int compare(final byte[] a, final int astart, final int alength, final int chunknumber) {
assert (chunknumber < chunkcount);
final int l = Math.min(this.rowdef.primaryKeyLength, Math.min(a.length - astart, alength));
- return rowdef.objectOrder.compare(a, astart, l, chunkcache, chunknumber * this.rowdef.objectsize, this.rowdef.primaryKeyLength);
+ return rowdef.objectOrder.compare(a, astart, chunkcache, chunknumber * this.rowdef.objectsize, l);
}
protected final boolean match(final int i, final int j) {
diff --git a/source/net/yacy/kelondro/index/RowSet.java b/source/net/yacy/kelondro/index/RowSet.java
index e345596f2..3100513a3 100644
--- a/source/net/yacy/kelondro/index/RowSet.java
+++ b/source/net/yacy/kelondro/index/RowSet.java
@@ -77,8 +77,11 @@ public class RowSet extends RowCollection implements ObjectIndex, Iterable<Row.E
assert orderbound >= 0 : "orderbound = " + orderbound;
if (orderbound < 0) return new RowSet(rowdef);
final byte[] chunkcache = new byte[size * rowdef.objectsize];
- assert b.length - exportOverheadSize == size * rowdef.objectsize;
- if (b.length - exportOverheadSize != size * rowdef.objectsize) return new RowSet(rowdef);
+ //assert b.length - exportOverheadSize == size * rowdef.objectsize : "b.length = " + b.length + ", size * rowdef.objectsize = " + size * rowdef.objectsize;
+ if (b.length - exportOverheadSize != size * rowdef.objectsize) {
+ Log.logSevere("RowSet", "exportOverheadSize wrong: b.length = " + b.length + ", size * rowdef.objectsize = " + size * rowdef.objectsize);
+ return new RowSet(rowdef);
+ }
System.arraycopy(b, exportOverheadSize, chunkcache, 0, chunkcache.length);
return new RowSet(rowdef, size, chunkcache, orderbound);
}
@@ -201,22 +204,17 @@ public class RowSet extends RowCollection implements ObjectIndex, Iterable<Row.E
sort();
}
- if ((this.rowdef.objectOrder != null) && (this.rowdef.objectOrder instanceof Base64Order) && (this.sortBound > 4000)) {
+ if (this.rowdef.objectOrder != null && this.rowdef.objectOrder instanceof Base64Order) {
// first try to find in sorted area
assert this.rowdef.objectOrder.wellformed(a, astart, alength) : "not wellformed: " + new String(a, astart, alength);
- final int p = binarySearch(a, astart, alength);
- if (p >= 0) return p;
-
- // then find in unsorted area
- return iterativeSearch(a, astart, alength, this.sortBound, this.chunkcount);
- } else {
- // first try to find in sorted area
- final int p = binarySearch(a, astart, alength);
- if (p >= 0) return p;
+ }
- // then find in unsorted area
- return iterativeSearch(a, astart, alength, this.sortBound, this.chunkcount);
- }
+ // first try to find in sorted area
+ final int p = binarySearch(a, astart, alength);
+ if (p >= 0) return p;
+
+ // then find in unsorted area
+ return iterativeSearch(a, astart, alength, this.sortBound, this.chunkcount);
}
private final int iterativeSearch(final byte[] key, final int astart, final int alength, final int leftBorder, final int rightBound) {
@@ -386,25 +384,8 @@ public class RowSet extends RowCollection implements ObjectIndex, Iterable<Row.E
*/
public final RowSet merge(final RowSet c) throws RowSpaceExceededException {
assert c != null;
- /*
- if (this.isSorted() && this.size() >= c.size()) {
- return mergeInsert(this, c);
- }*/
return mergeEnum(this, c);
}
- /*
- private static kelondroRowSet mergeInsert(kelondroRowSet sorted, kelondroRowCollection small) {
- assert sorted.rowdef == small.rowdef;
- assert sorted.isSorted();
- assert small.size() <= sorted.size();
- sorted.ensureSize(sorted.size() + small.size());
- for (int i = 0; i < small.size(); i++) {
-
- }
-
- return sorted;
- }
-*/
/**
* merge this row collection with another row collection using an simultanous iteration of the input collections
@@ -436,7 +417,7 @@ public class RowSet extends RowCollection implements ObjectIndex, Iterable<Row.E
c0p = c0i * objectsize;
c1p = c1i * objectsize;
o = c0.rowdef.objectOrder.compare(
- c0.chunkcache, c0p, c0.rowdef.primaryKeyLength,
+ c0.chunkcache, c0p,
c1.chunkcache, c1p, c0.rowdef.primaryKeyLength);
if (o == 0) {
r.addSorted(c0.chunkcache, c0p, objectsize);
diff --git a/source/net/yacy/kelondro/index/RowSetArray.java b/source/net/yacy/kelondro/index/RowSetArray.java
index 574c78887..14236fd80 100644
--- a/source/net/yacy/kelondro/index/RowSetArray.java
+++ b/source/net/yacy/kelondro/index/RowSetArray.java
@@ -27,24 +27,39 @@ import java.util.Iterator;
import java.util.List;
import net.yacy.kelondro.index.Row.Entry;
+import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.CloneableIterator;
import net.yacy.kelondro.order.MergeIterator;
import net.yacy.kelondro.order.StackIterator;
-public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
+public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry>, Cloneable {
private final Row rowdef;
- private final RowSet[] array;
+ private final ObjectIndexCache[] array;
public RowSetArray(final Row rowdef, final int arraySize) {
- this.array = new RowSet[arraySize];
+ //assert arraySize < 100 : arraySize;
+ this.array = new ObjectIndexCache[arraySize];
this.rowdef = rowdef;
for (int i = 0; i < arraySize; i++) {
- this.array[i] = null;
+ this.array[i] = new ObjectIndexCache(rowdef, 0);
}
}
+ private RowSetArray(final Row rowdef, final ObjectIndexCache[] array) {
+ this.array = array;
+ this.rowdef = rowdef;
+ }
+
+ public RowSetArray clone() {
+ ObjectIndexCache[] a = new ObjectIndexCache[this.array.length];
+ for (int i = 0; i < this.array.length; i++) {
+ a[i] = this.array[i].clone();
+ }
+ return new RowSetArray(this.rowdef, a);
+ }
+
private final int indexFor(final byte[] key) {
return (int) (this.rowdef.objectOrder.cardinal(key) % ((long) array.length));
}
@@ -53,10 +68,34 @@ public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
return (int) (this.rowdef.objectOrder.cardinal(row.bytes(), 0, row.getPrimaryKeyLength()) % ((long) array.length));
}
- private final RowSet accessArray(final int i) {
- RowSet r = this.array[i];
+ public final byte[] smallestKey() {
+ HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.array.length);
+ synchronized (this.array) {
+ for (ObjectIndexCache rs: this.array) try {
+ keysort.put(rs.smallestKey());
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ }
+ }
+ return keysort.smallestKey();
+ }
+
+ public final byte[] largestKey() {
+ HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.array.length);
+ synchronized (this.array) {
+ for (ObjectIndexCache rs: this.array) try {
+ keysort.put(rs.largestKey());
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ }
+ }
+ return keysort.largestKey();
+ }
+
+ private final ObjectIndexCache accessArray(final int i) {
+ ObjectIndexCache r = this.array[i];
if (r == null) synchronized (this.array) {
- r = new RowSet(this.rowdef);
+ r = new ObjectIndexCache(this.rowdef, 0);
this.array[i] = r;
}
return r;
@@ -97,7 +136,7 @@ public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
public final Entry get(final byte[] key) {
final int i = indexFor(key);
if (i < 0) return null;
- final RowSet r = this.array[i];
+ final ObjectIndexCache r = this.array[i];
if (r == null) return null;
return r.get(key);
}
@@ -105,7 +144,7 @@ public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
public final boolean has(final byte[] key) {
final int i = indexFor(key);
if (i < 0) return false;
- final RowSet r = this.array[i];
+ final ObjectIndexCache r = this.array[i];
if (r == null) return false;
return r.has(key);
}
@@ -115,7 +154,6 @@ public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
final Collection<CloneableIterator<byte[]>> col = new ArrayList<CloneableIterator<byte[]>>();
for (int i = 0; i < this.array.length; i++) {
if (this.array[i] != null) {
- this.array[i].sort();
col.add(this.array[i].keys(up, firstKey));
}
}
@@ -171,13 +209,15 @@ public final class RowSetArray implements ObjectIndex, Iterable<Row.Entry> {
return this.rowdef;
}
+ @SuppressWarnings("unchecked")
public final CloneableIterator<Entry> rows(final boolean up, final byte[] firstKey) {
synchronized (this.array) {
- final Collection<CloneableIterator<Entry>> col = new ArrayList<CloneableIterator<Entry>>();
+ final CloneableIterator<Entry>[] col = new CloneableIterator[this.array.length];
for (int i = 0; i < this.array.length; i++) {
- if (this.array[i] != null) {
- this.array[i].sort();
- col.add(this.array[i].rows(up, firstKey));
+ if (this.array[i] == null) {
+ col[i] = null;
+ } else {
+ col[i] = this.array[i].rows(up, firstKey);
}
}
return StackIterator.stack(col);
diff --git a/source/net/yacy/kelondro/order/AbstractOrder.java b/source/net/yacy/kelondro/order/AbstractOrder.java
index 3e4134fe6..c80779a3d 100644
--- a/source/net/yacy/kelondro/order/AbstractOrder.java
+++ b/source/net/yacy/kelondro/order/AbstractOrder.java
@@ -66,4 +66,12 @@ public abstract class AbstractOrder<A> implements Order<A> {
public int hashCode() {
return this.signature().hashCode();
}
+
+ public A smallest(A a, A b) {
+ return (compare(a, b) > 0) ? b : a;
+ }
+
+ public A largest(A a, A b) {
+ return (compare(a, b) > 0) ? a : b;
+ }
}
diff --git a/source/net/yacy/kelondro/order/Base64Order.java b/source/net/yacy/kelondro/order/Base64Order.java
index aa2e160e4..8951ac605 100644
--- a/source/net/yacy/kelondro/order/Base64Order.java
+++ b/source/net/yacy/kelondro/order/Base64Order.java
@@ -89,7 +89,7 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
}
public HandleSet getHandleSet(final int keylength, final int space) throws RowSpaceExceededException {
- return new HandleSet(keylength, this, space, space);
+ return new HandleSet(keylength, this, space);
}
public static byte[] zero(int length) {
@@ -416,9 +416,9 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
public final int compare(final byte[] a, final byte[] b) {
try {
return (asc) ?
- ((zero == null) ? compares(a, b) : compare0(a, 0, a.length, b, 0, b.length))
+ ((zero == null) ? compares(a, b) : compare0(a, 0, b, 0, a.length))
:
- ((zero == null) ? compares(b, a) : compare0(b, 0, b.length, a, 0, a.length));
+ ((zero == null) ? compares(b, a) : compare0(b, 0, a, 0, a.length));
} catch (Exception e) {
// if a or b is not well-formed, an ArrayIndexOutOfBoundsException may occur
// in that case we don't want that the exception makes databse functions
@@ -439,16 +439,16 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
}
}
- public final int compare(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
+ public final int compare(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
try {
return (asc) ?
- compare0(a, aoffset, alength, b, boffset, blength)
+ compare0(a, aoffset, b, boffset, length)
:
- compare0(b, boffset, blength, a, aoffset, alength);
+ compare0(b, boffset, a, aoffset, length);
} catch (Exception e) {
// same handling as in simple compare method above
- boolean wfa = wellformed(a, aoffset, alength);
- boolean wfb = wellformed(b, boffset, blength);
+ boolean wfa = wellformed(a, aoffset, length);
+ boolean wfb = wellformed(b, boffset, length);
if (wfa && wfb) {
// uh strange. throw the exception
if (e instanceof ArrayIndexOutOfBoundsException) throw (ArrayIndexOutOfBoundsException) e;
@@ -456,17 +456,17 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
}
if (wfa) return (asc) ? -1 : 1;
if (wfb) return (asc) ? 1 : -1;
- return ((asc) ? 1 : -1) * NaturalOrder.naturalOrder.compare(a, aoffset, alength, b, boffset, blength);
+ return ((asc) ? 1 : -1) * NaturalOrder.naturalOrder.compare(a, aoffset, b, boffset, length);
}
}
- private final int compare0(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
- if (zero == null) return compares(a, aoffset, alength, b, boffset, blength);
+ private final int compare0(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
+ if (zero == null) return compares(a, aoffset, b, boffset, length);
// we have an artificial start point. check all combinations
- final int az = compares(a, aoffset, alength, zero, 0, Math.min(alength, zero.length)); // -1 if a < z; 0 if a == z; 1 if a > z
- final int bz = compares(b, boffset, blength, zero, 0, Math.min(blength, zero.length)); // -1 if b < z; 0 if b == z; 1 if b > z
- if (az == bz) return compares(a, aoffset, alength, b, boffset, blength);
+ final int az = compares(a, aoffset, zero, 0, Math.min(length, zero.length)); // -1 if a < z; 0 if a == z; 1 if a > z
+ final int bz = compares(b, boffset, zero, 0, Math.min(length, zero.length)); // -1 if b < z; 0 if b == z; 1 if b > z
+ if (az == bz) return compares(a, aoffset, b, boffset, length);
return sig(az - bz);
}
@@ -497,24 +497,21 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
return 0;
}
- private final int compares(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
- assert (aoffset + alength <= a.length) : "a.length = " + a.length + ", aoffset = " + aoffset + ", alength = " + alength;
- assert (boffset + blength <= b.length) : "b.length = " + b.length + ", boffset = " + boffset + ", blength = " + blength;
+ private final int compares(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
+ assert (aoffset + length <= a.length) : "a.length = " + a.length + ", aoffset = " + aoffset + ", alength = " + length;
+ assert (boffset + length <= b.length) : "b.length = " + b.length + ", boffset = " + boffset + ", blength = " + length;
assert (ahpla.length == 128);
short i = 0;
- final int al = Math.min(alength, a.length - aoffset);
- final int bl = Math.min(blength, b.length - boffset);
- final short ml = (short) Math.min(al, bl);
byte ac, bc;
//byte acc, bcc;
//int c = 0;
- while (i < ml) {
- assert (i + aoffset < a.length) : "i = " + i + ", aoffset = " + aoffset + ", a.length = " + a.length + ", a = " + NaturalOrder.arrayList(a, aoffset, al);
- assert (i + boffset < b.length) : "i = " + i + ", boffset = " + boffset + ", b.length = " + b.length + ", b = " + NaturalOrder.arrayList(b, boffset, al);
+ while (i < length) {
+ assert (i + aoffset < a.length) : "i = " + i + ", aoffset = " + aoffset + ", a.length = " + a.length + ", a = " + NaturalOrder.arrayList(a, aoffset, length);
+ assert (i + boffset < b.length) : "i = " + i + ", boffset = " + boffset + ", b.length = " + b.length + ", b = " + NaturalOrder.arrayList(b, boffset, length);
ac = a[aoffset + i];
- assert (ac >= 0) && (ac < 128) : "ac = " + ac + ", a = " + NaturalOrder.arrayList(a, aoffset, al);
+ assert (ac >= 0) && (ac < 128) : "ac = " + ac + ", a = " + NaturalOrder.arrayList(a, aoffset, length);
bc = b[boffset + i];
- assert (bc >= 0) && (bc < 128) : "bc = " + bc + ", b = " + NaturalOrder.arrayList(b, boffset, al);
+ assert (bc >= 0) && (bc < 128) : "bc = " + bc + ", b = " + NaturalOrder.arrayList(b, boffset, length);
assert ac != 0;
assert bc != 0;
//if ((ac == 0) && (bc == 0)) return 0; // zero-terminated length
@@ -534,9 +531,6 @@ public class Base64Order extends AbstractOrder<byte[]> implements ByteOrder, Com
//return c;
return ab[(ac << 7) | bc];
}
- // compare length
- if (al > bl) return 1;
- if (al < bl) return -1;
// they are equal
return 0;
}
diff --git a/source/net/yacy/kelondro/order/Bitfield.java b/source/net/yacy/kelondro/order/Bitfield.java
index 345f8b66d..c4781a765 100644
--- a/source/net/yacy/kelondro/order/Bitfield.java
+++ b/source/net/yacy/kelondro/order/Bitfield.java
@@ -83,7 +83,7 @@ public class Bitfield implements Cloneable {
public boolean get(final int pos) {
assert (pos >= 0);
final int slot = pos >> 3; // /8
- if (slot > bb.length) return false;
+ if (slot >= bb.length) return false;
return (bb[slot] & (1 << (pos % 8))) > 0;
}
diff --git a/source/net/yacy/kelondro/order/ByteOrder.java b/source/net/yacy/kelondro/order/ByteOrder.java
index 4500e7ee3..ab249fa13 100644
--- a/source/net/yacy/kelondro/order/ByteOrder.java
+++ b/source/net/yacy/kelondro/order/ByteOrder.java
@@ -36,8 +36,10 @@ public interface ByteOrder extends Order<byte[]> {
public boolean wellformed(byte[] a);
public boolean wellformed(byte[] a, int start, int len);
+
+ public int compare(byte[] a, byte[] b);
- public int compare(byte[] a, int astart, int alen, byte[] b, int bstart, int blen);
+ public int compare(byte[] a, int astart, byte[] b, int bstart, int len);
public boolean equal(final byte[] a, final byte[] b);
@@ -47,4 +49,7 @@ public interface ByteOrder extends Order<byte[]> {
public HandleSet getHandleSet(final int keylength, final int space) throws RowSpaceExceededException;
+ public byte[] smallest(byte[] a, byte[] b);
+
+ public byte[] largest(byte[] a, byte[] b);
}
diff --git a/source/net/yacy/kelondro/order/NaturalOrder.java b/source/net/yacy/kelondro/order/NaturalOrder.java
index c3915ccd0..f7dedca81 100644
--- a/source/net/yacy/kelondro/order/NaturalOrder.java
+++ b/source/net/yacy/kelondro/order/NaturalOrder.java
@@ -42,7 +42,7 @@ public final class NaturalOrder extends AbstractOrder<byte[]> implements ByteOrd
}
public HandleSet getHandleSet(final int keylength, final int space) throws RowSpaceExceededException {
- return new HandleSet(keylength, this, space, space);
+ return new HandleSet(keylength, this, space);
}
public boolean wellformed(final byte[] a) {
@@ -78,17 +78,7 @@ public final class NaturalOrder extends AbstractOrder<byte[]> implements ByteOrd
if ( asc) return "nu";
return null;
}
- /*
- private final static long cardinalI(final byte[] key) {
- // returns a cardinal number in the range of 0 .. Long.MAX_VALUE
- long c = 0;
- int p = 0;
- while ((p < 8) && (p < key.length)) c = (c << 8) | ((long) key[p++] & 0xFF);
- while (p++ < 8) c = (c << 8);
- c = c >>> 1;
- return c;
- }
- */
+
private final static long cardinalI(final byte[] key, int off, int len) {
// returns a cardinal number in the range of 0 .. Long.MAX_VALUE
long c = 0;
@@ -159,19 +149,31 @@ public final class NaturalOrder extends AbstractOrder<byte[]> implements ByteOrd
// two arrays are also equal if one array is a subset of the other's array
// with filled-up char(0)-values
public final int compare(final byte[] a, final byte[] b) {
- return (asc) ? compare0(a, 0, a.length, b, 0, b.length) : compare0(b, 0, b.length, a, 0, a.length);
+ if (a.length == b.length) {
+ return (asc) ? compare0(a, 0, b, 0, a.length) : compare0(b, 0, a, 0, a.length);
+ }
+ int length = Math.min(a.length, b.length);
+ if (asc) {
+ int c = compare0(a, 0, b, 0, length);
+ if (c != 0) return c;
+ return (a.length > b.length) ? 1 : -1;
+ }
+ int c = compare0(b, 0, a, 0, length);
+ if (c != 0) return c;
+ return (a.length > b.length) ? -1 : 1;
}
- public final int compare(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
- return (asc) ? compare0(a, aoffset, alength, b, boffset, blength) : compare0(b, boffset, blength, a, aoffset, alength);
+ public final int compare(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
+ return (asc) ? compare0(a, aoffset, b, boffset, length) : compare0(b, boffset, a, aoffset, length);
}
- public final int compare0(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
- if (zero == null) return compares(a, aoffset, alength, b, boffset, blength);
+ public final int compare0(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
+ if (zero == null) return compares(a, aoffset, b, boffset, length);
// we have an artificial start point. check all combinations
- final int az = compares(a, aoffset, alength, zero, 0, zero.length); // -1 if a < z; 0 if a == z; 1 if a > z
- final int bz = compares(b, boffset, blength, zero, 0, zero.length); // -1 if b < z; 0 if b == z; 1 if b > z
- if (az == bz) return compares(a, aoffset, alength, b, boffset, blength);
+ assert length == zero.length;
+ final int az = compares(a, aoffset, zero, 0, length); // -1 if a < z; 0 if a == z; 1 if a > z
+ final int bz = compares(b, boffset, zero, 0, length); // -1 if b < z; 0 if b == z; 1 if b > z
+ if (az == bz) return compares(a, aoffset, b, boffset, length);
return sig(az - bz);
}
@@ -197,12 +199,10 @@ public final class NaturalOrder extends AbstractOrder<byte[]> implements ByteOrd
return true;
}
- public static final int compares(final byte[] a, final int aoffset, final int alength, final byte[] b, final int boffset, final int blength) {
+ public static final int compares(final byte[] a, final int aoffset, final byte[] b, final int boffset, final int length) {
int i = 0;
- final int al = Math.min(alength, a.length - aoffset);
- final int bl = Math.min(blength, b.length - boffset);
int aa, bb;
- while ((i < al) && (i < bl)) {
+ while (i < length) {
aa = 0xff & a[i + aoffset];
bb = 0xff & b[i + boffset];
if (aa > bb) return 1;
@@ -210,9 +210,6 @@ public final class NaturalOrder extends AbstractOrder<byte[]> implements ByteOrd
// else the bytes are equal and it may go on yet undecided
i++;
}
- // compare length
- if (al > bl) return 1;
- if (al < bl) return -1;
// they are equal
return 0;
}
diff --git a/source/net/yacy/kelondro/order/StackIterator.java b/source/net/yacy/kelondro/order/StackIterator.java
index beb2e832e..bb528bbf8 100644
--- a/source/net/yacy/kelondro/order/StackIterator.java
+++ b/source/net/yacy/kelondro/order/StackIterator.java
@@ -87,19 +87,24 @@ public class StackIterator<E> implements CloneableIterator<E> {
throw new java.lang.UnsupportedOperationException("merge does not support remove");
}
- public static <A> CloneableIterator<A> stack(final Collection<CloneableIterator<A>> iterators) {
+ @SuppressWarnings("unchecked")
+ public static <A> CloneableIterator<A> stack(final CloneableIterator<A>[] iterators) {
// this extends the ability to combine two iterators
// to the ability of combining a set of iterators
if (iterators == null) return null;
- if (iterators.isEmpty()) return null;
- return stack(iterators.iterator());
- }
-
- private static <A> CloneableIterator<A> stack(final Iterator<CloneableIterator<A>> iiterators) {
- if (iiterators == null) return null;
- if (!(iiterators.hasNext())) return null;
- final CloneableIterator<A> one = iiterators.next();
- if (!(iiterators.hasNext())) return one;
- return new StackIterator<A>(one, stack(iiterators));
+ if (iterators.length == 0) return null;
+ if (iterators.length == 1) {
+ return iterators[0];
+ }
+ if (iterators.length == 2) {
+ if (iterators[0] == null) return iterators[1];
+ if (iterators[1] == null) return iterators[0];
+ return new StackIterator<A>(iterators[0], iterators[1]);
+ }
+ CloneableIterator<A> a = iterators[0];
+ final CloneableIterator<A>[] iterators0 = new CloneableIterator[iterators.length - 1];
+ System.arraycopy(iterators, 1, iterators0, 0, iterators.length - 1);
+ if (a == null) return stack(iterators0);
+ return new StackIterator<A>(a, stack(iterators0));
}
}
diff --git a/source/net/yacy/kelondro/table/SQLTable.java b/source/net/yacy/kelondro/table/SQLTable.java
index 6a335a182..6474bb786 100644
--- a/source/net/yacy/kelondro/table/SQLTable.java
+++ b/source/net/yacy/kelondro/table/SQLTable.java
@@ -102,7 +102,15 @@ public class SQLTable implements ObjectIndex, Iterable<Row.Entry> {
}
}
+
+ public byte[] smallestKey() {
+ return null;
+ }
+ public byte[] largestKey() {
+ return null;
+ }
+
public String filename() {
return "dbtest." + theDBConnection.hashCode();
}
diff --git a/source/net/yacy/kelondro/table/SplitTable.java b/source/net/yacy/kelondro/table/SplitTable.java
index f3c7206c5..aee24d286 100644
--- a/source/net/yacy/kelondro/table/SplitTable.java
+++ b/source/net/yacy/kelondro/table/SplitTable.java
@@ -43,9 +43,8 @@ import java.util.concurrent.TimeUnit;
import net.yacy.kelondro.blob.ArrayStack;
import net.yacy.kelondro.index.Cache;
-import net.yacy.kelondro.index.Column;
+import net.yacy.kelondro.index.HandleSet;
import net.yacy.kelondro.index.ObjectIndex;
-import net.yacy.kelondro.index.ObjectIndexCache;
import net.yacy.kelondro.index.Row;
import net.yacy.kelondro.index.RowCollection;
import net.yacy.kelondro.index.RowSpaceExceededException;
@@ -53,7 +52,6 @@ import net.yacy.kelondro.index.Row.Entry;
import net.yacy.kelondro.logging.Log;
import net.yacy.kelondro.order.CloneableIterator;
import net.yacy.kelondro.order.MergeIterator;
-import net.yacy.kelondro.order.NaturalOrder;
import net.yacy.kelondro.order.Order;
import net.yacy.kelondro.order.StackIterator;
import net.yacy.kelondro.util.DateFormatter;
@@ -68,7 +66,6 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
// the table type can be either kelondroFlex or kelondroEco
private static final int EcoFSBufferSize = 20;
- static final ObjectIndex dummyIndex = new ObjectIndexCache(new Row(new Column[]{new Column("key", Column.celltype_binary, Column.encoder_bytes, 2, "key")}, NaturalOrder.naturalOrder), 0);
// the thread pool for the keeperOf executor service
private ExecutorService executor;
@@ -83,8 +80,6 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
private long fileSizeLimit;
private boolean useTailCache;
private boolean exceed134217727;
- //private BlockingQueue<DiscoverOrder> orderQueue;
- //private Discovery[] discoveryThreads;
public SplitTable(
final File path,
@@ -95,7 +90,7 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
this(path, tablename, rowdef, ArrayStack.oneMonth, (long) Integer.MAX_VALUE, useTailCache, exceed134217727);
}
- public SplitTable(
+ private SplitTable(
final File path,
final String tablename,
final Row rowdef,
@@ -111,22 +106,34 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
this.useTailCache = useTailCache;
this.exceed134217727 = exceed134217727;
this.entryOrder = new Row.EntryComparator(rowdef.objectOrder);
- /*
- this.orderQueue = new LinkedBlockingQueue<DiscoverOrder>();
- this.discoveryThreads = new Discovery[Runtime.getRuntime().availableProcessors() + 1];
- for (int i = 0; i < this.discoveryThreads.length; i++) {
- this.discoveryThreads[i] = new Discovery(this.orderQueue);
- this.discoveryThreads[i].start();
- }
- */
init();
}
- String newFilename() {
+ public final byte[] smallestKey() {
+ HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());
+ for (ObjectIndex oi: this.tables.values()) try {
+ keysort.put(oi.smallestKey());
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ }
+ return keysort.smallestKey();
+ }
+
+ public final byte[] largestKey() {
+ HandleSet keysort = new HandleSet(this.rowdef.primaryKeyLength, this.rowdef.objectOrder, this.tables.size());
+ for (ObjectIndex oi: this.tables.values()) try {
+ keysort.put(oi.largestKey());
+ } catch (RowSpaceExceededException e) {
+ Log.logException(e);
+ }
+ return keysort.largestKey();
+ }
+
+ private String newFilename() {
return prefix + "." + DateFormatter.formatShortMilliSecond(new Date()) + ".table";
}
- public void init() throws RowSpaceExceededException {
+ private void init() throws RowSpaceExceededException {
current = null;
// initialized tables map
@@ -286,11 +293,11 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
return this.rowdef;
}
- public synchronized boolean has(final byte[] key) {
+ public boolean has(final byte[] key) {
return keeperOf(key) != null;
}
- public synchronized Row.Entry get(final byte[] key) throws IOException {
+ public Row.Entry get(final byte[] key) throws IOException {
final ObjectIndex keeper = keeperOf(key);
if (keeper == null) return null;
return keeper.get(key);
@@ -331,248 +338,43 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
return table;
}
- public synchronized Row.Entry replace(final Row.Entry row) throws IOException, RowSpaceExceededException {
+ public Row.Entry replace(final Row.Entry row) throws IOException, RowSpaceExceededException {
assert row.objectsize() <= this.rowdef.objectsize;
ObjectIndex keeper = keeperOf(row.getColBytes(0, true));
if (keeper != null) return keeper.replace(row);
- keeper = (this.current == null) ? newTable() : checkTable(this.tables.get(this.current));
+ synchronized (this.tables) {
+ keeper = (this.current == null) ? newTable() : checkTable(this.tables.get(this.current));
+ }
keeper.put(row);
return null;
}
- public synchronized void put(final Row.Entry row) throws IOException, RowSpaceExceededException {
+ public void put(final Row.Entry row) throws IOException, RowSpaceExceededException {
assert row.objectsize() <= this.rowdef.objectsize;
ObjectIndex keeper = keeperOf(row.getColBytes(0, true));
if (keeper != null) {keeper.put(row); return;}
- assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;
- keeper = (this.current == null) ? newTable() : checkTable(this.tables.get(this.current));
- keeper.put(row);
- }
-
- /**
- * challenge class for concurrent keeperOf implementation
- *
- */
- /*
- private static final class Challenge {
- // the Challenge is a discover order entry
- private final byte[] key;
- private int responseCounter, finishCounter;
- private ObjectIndex discovery;
- private Semaphore readyCheck;
- public Challenge(final byte[] key, int finishCounter) {
- this.key = key;
- this.responseCounter = 0;
- this.finishCounter = finishCounter;
- this.readyCheck = new Semaphore(0);
- this.discovery = null;
- }
- public byte[] getKey() {
- return this.key;
- }
- public synchronized void commitNoDiscovery() {
- this.responseCounter++;
- if (this.responseCounter >= this.finishCounter) this.readyCheck.release();
- }
- public synchronized void commitDiscovery(ObjectIndex discovery) {
- this.responseCounter++;
- this.discovery = discovery;
- this.readyCheck.release();
- }
- public ObjectIndex discover(long timeout) {
- if (this.discovery != null) return this.discovery;
- try {
- this.readyCheck.tryAcquire(1, timeout, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {}
- return this.discovery;
- }
- }
- */
-
- /**
- * A DiscoverOrder is a class to order a check for a specific table
- * for the occurrences of a given key
- *
- */
- /*
- private static final class DiscoverOrder {
- public Challenge challenge;
- public ObjectIndex objectIndex;
- public DiscoverOrder() {
- this.challenge = null;
- this.objectIndex = null;
- }
- public DiscoverOrder(Challenge challenge, ObjectIndex objectIndex) {
- this.challenge = challenge;
- this.objectIndex = objectIndex;
- }
- public void executeOrder() {
- try {
- if (this.objectIndex.has(this.challenge.getKey())) {
- this.challenge.commitDiscovery(this.objectIndex);
- } else {
- this.challenge.commitNoDiscovery();
- }
- } catch (Exception e) {
- Log.logSevere("SplitTable", "", e);
- this.challenge.commitNoDiscovery();
- }
- }
- }
- private static final DiscoverOrder poisonDiscoverOrder = new DiscoverOrder();
- */
-
- /**
- * the Discovery class is used to start some concurrent threads that check the database
- * table files for occurrences of key after a keeperOf was submitted
- *
- */
- /*
- private static final class Discovery extends Thread {
- // the class discovers keeper locations in the splitted table
- BlockingQueue<DiscoverOrder> orderQueue;
- public Discovery(BlockingQueue<DiscoverOrder> orderQueue) {
- super("SplitTable-Discovery");
- this.orderQueue = orderQueue;
- }
- public void run() {
- DiscoverOrder order;
- while (true) {
- try {
- order = orderQueue.take();
- if (order == poisonDiscoverOrder) break;
- // check if in the given objectIndex is the key as given in the order
- order.executeOrder();
- } catch (InterruptedException e) {
- Log.logSevere("SplitTable", "", e);
- //continue;
- break;
- }
- }
- Log.logInfo("SplitTable.Discovery", "terminated discovery thread " + this.getName());
+ synchronized (this.tables) {
+ assert this.current == null || this.tables.get(this.current) != null : "this.current = " + this.current;
+ keeper = (this.current == null) ? newTable() : checkTable(this.tables.get(this.current));
}
+ keeper.put(row);
}
- private boolean discoveriesAlive() {
- for (int i = 0; i < this.discoveryThreads.length; i++) {
- if (!this.discoveryThreads[i].isAlive()) return false;
- }
- return true;
- }
- */
private ObjectIndex keeperOf(final byte[] key) {
- //if (!discoveriesAlive()) {
- //synchronized (tables) {
if (key == null) return null;
- for (ObjectIndex oi: tables.values()) {
- if (oi.has(key)) return oi;
- }
- return null;
- //}
- //}
- /*
- Challenge challenge = null;
- synchronized (tables) {
- int tableCount = this.tables.size();
- challenge = new Challenge(key, tableCount);
-
- // submit discover orders to the processing units
- final Iterator<ObjectIndex> i = tables.values().iterator();
- DiscoverOrder order;
- boolean offered;
- while (i.hasNext()) {
- order = new DiscoverOrder(challenge, i.next());
- offered = this.orderQueue.offer(order);
- if (!offered) {
- // for some reason the queue did not accept the order
- // so we execute the order here
- order.executeOrder();
- Log.logWarning("SplitTable", "executed a challenge order without concurrency. queue size = " + this.orderQueue.size());
- }
- }
- }
- // wait for a result
- ObjectIndex result = challenge.discover(1000);
- //System.out.println("result of discovery: file = " + ((result == null) ? "null" : result.filename()));
- return result;
- */
- }
-
- /*
- private static final class ReadyCheck {
- private boolean r;
- public ReadyCheck() {
- this.r = false;
- }
- public void isReady() {
- this.r = true;
- }
- public boolean check() {
- return this.r;
- }
- }
- private ObjectIndex keeperOf(final byte[] key) {
-
- if (tables.size() < 2) {
- // no concurrency if not needed
- for (final ObjectIndex table : tables.values()) {
- if (table.has(key)) return table;
- }
- return null;
- }
-
- // because the index is stored only in one table,
- // and the index is completely in RAM, a concurrency will create
- // not concurrent File accesses
-
- // start a concurrent query to database tables
- final CompletionService<ObjectIndex> cs = new ExecutorCompletionService<ObjectIndex>(executor);
- int accepted = 0;
- final ReadyCheck ready = new ReadyCheck();
- for (final ObjectIndex table : tables.values()) {
- if (ready.check()) break; // found already a table
- try {
- cs.submit(new Callable<ObjectIndex>() {
- public ObjectIndex call() {
- if (table.has(key)) {
- ready.isReady();
- return table;
- }
- return dummyIndex;
- }
- });
- accepted++;
- } catch (final RejectedExecutionException e) {
- // the executor is either shutting down or the blocking queue is full
- // execute the search direct here without concurrency
- if (table.has(key)) return table;
- }
- }
-
- // read the result
- try {
- for (int i = 0; i < accepted; i++) {
- final Future<ObjectIndex> f = cs.take();
- if (f == null) continue;
- final ObjectIndex index = f.get();
- if (index == dummyIndex) continue;
- return index;
- }
- return null;
- } catch (final InterruptedException e) {
- Thread.currentThread().interrupt();
- } catch (final ExecutionException e) {
- Log.logSevere("SplitTable", "", e);
- throw new RuntimeException(e.getCause());
+ for (ObjectIndex oi: tables.values()) {
+ if (oi.has(key)) return oi;
}
return null;
}
- */
- public synchronized void addUnique(final Row.Entry row) throws IOException, RowSpaceExceededException {
+
+ public void addUnique(final Row.Entry row) throws IOException, RowSpaceExceededException {
assert row.objectsize() <= this.rowdef.objectsize;
ObjectIndex table = (this.current == null) ? null : tables.get(this.current);
- if (table == null) table = newTable(); else table = checkTable(table);
+ synchronized (this.tables) {
+ if (table == null) table = newTable(); else table = checkTable(table);
+ }
table.addUnique(row);
}
@@ -585,13 +387,13 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
return report;
}
- public synchronized Row.Entry remove(final byte[] key) throws IOException {
+ public Row.Entry remove(final byte[] key) throws IOException {
final ObjectIndex table = keeperOf(key);
if (table == null) return null;
return table.remove(key);
}
- public synchronized Row.Entry removeOne() throws IOException {
+ public Row.Entry removeOne() throws IOException {
final Iterator<ObjectIndex> i = tables.values().iterator();
ObjectIndex table, maxtable = null;
int maxcount = -1;
@@ -608,7 +410,7 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
return maxtable.removeOne();
}
- public synchronized CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
+ public CloneableIterator<byte[]> keys(final boolean up, final byte[] firstKey) throws IOException {
final List<CloneableIterator<byte[]>> c = new ArrayList<CloneableIterator<byte[]>>(tables.size());
final Iterator<ObjectIndex> i = tables.values().iterator();
CloneableIterator<byte[]> k;
@@ -619,7 +421,7 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
return MergeIterator.cascade(c, rowdef.objectOrder, MergeIterator.simpleMerge, up);
}
- public synchronized CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
+ public CloneableIterator<Row.Entry> rows(final boolean up, final byte[] firstKey) throws IOException {
final List<CloneableIterator<Row.Entry>> c = new ArrayList<CloneableIterator<Row.Entry>>(tables.size());
final Iterator<ObjectIndex> i = tables.values().iterator();
while (i.hasNext()) {
@@ -636,26 +438,18 @@ public class SplitTable implements ObjectIndex, Iterable<Row.Entry> {
}
}
+ @SuppressWarnings("unchecked")
public synchronized CloneableIterator<Row.Entry> rows() throws IOException {
- final List<CloneableIterator<Row.Entry>> c = new ArrayList<CloneableIterator<Row.Entry>>(tables.size());
+ final CloneableIterator<Row.Entry>[] c = new CloneableIterator[tables.size()];
final Iterator<ObjectIndex> i = tables.values().iterator();
+ int d = 0;
while (i.hasNext()) {
- c.add(i.next().rows());
+ c[d++] = i.next().rows();
}
return StackIterator.stack(c);
}
public synchronized void close() {
- // stop discover threads
- /*
- if (this.orderQueue != null) for (int i = 0; i < this.discoveryThreads.length; i++) {
- try {
- this.orderQueue.put(poisonDiscoverOrder);
- } catch (InterruptedException e) {
- Log.logSevere("SplitTable", "", e);
- }
- }
- */
if (tables == null) return;
this.executor.shutdown();
try {
diff --git a/source/net/yacy/kelondro/table/Table.java b/source/net/yacy/kelondro/table/Table.java
index 2c961f300..c7e061d22 100644
--- a/source/net/yacy/kelondro/table/Table.java
+++ b/source/net/yacy/kelondro/table/Table.java
@@ -252,6 +252,14 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
return MemoryControl.available() < minmemremaining;
}
+ public byte[] smallestKey() {
+ return this.index.smallestKey();
+ }
+
+ public byte[] largestKey() {
+ return this.index.largestKey();
+ }
+
public static long tableSize(final File tablefile, final int recordsize) throws IOException {
// returns number of records in table
return Records.tableSize(tablefile, recordsize);
@@ -272,7 +280,9 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
private final Map<String, String> memoryStats() {
// returns statistical data about this object
- assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
+ synchronized (table) {
+ assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
+ }
final HashMap<String, String> map = new HashMap<String, String>(8);
map.put("tableSize", Integer.toString(index.size()));
map.put("tableKeyChunkSize", Integer.toString(index.row().objectsize));
@@ -404,11 +414,24 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
public String filename() {
return this.file.filename().toString();
}
+
+ public Entry get(final byte[] key) throws IOException {
+ if ((file == null) || (index == null)) return null;
+ synchronized (this) {
+ assert file.size() == index.size() : "file.size() = " + file.size() + ", index.size() = " + index.size();
+ assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
+ }
+ Entry e = get0(key);
+ if (e != null && this.rowdef.objectOrder.equal(key, e.getPrimaryKeyBytes())) return e;
+ synchronized (this) {
+ e = get0(key);
+ assert e == null || this.rowdef.objectOrder.equal(key, e.getPrimaryKeyBytes());
+ return e;
+ }
+ }
- public synchronized Entry get(final byte[] key) throws IOException {
+ private Entry get0(final byte[] key) throws IOException {
if ((file == null) || (index == null)) return null;
- assert file.size() == index.size() : "file.size() = " + file.size() + ", index.size() = " + index.size();
- assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
final int i = (int) index.get(key);
if (i == -1) return null;
final byte[] b = new byte[rowdef.objectsize];
@@ -427,13 +450,15 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
return rowdef.newEntry(b);
}
- public synchronized boolean has(final byte[] key) {
+ public boolean has(final byte[] key) {
+ /*
try {
assert file.size() == index.size() : "file.size() = " + file.size() + ", index.size() = " + index.size();
} catch (final IOException e) {
Log.logSevere("Table", "", e);
}
assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
+ */
return index.has(key);
}
@@ -521,7 +546,7 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
assert table == null || table.size() == index.size() : "table.size() = " + table.size() + ", index.size() = " + index.size();
}
- public synchronized Entry put(final Entry row, final Date entryDate) throws IOException, RowSpaceExceededException {
+ public Entry put(final Entry row, final Date entryDate) throws IOException, RowSpaceExceededException {
return replace(row);
}
@@ -707,11 +732,11 @@ public class Table implements ObjectIndex, Iterable<Row.Entry> {
return this.rowdef;
}
- public synchronized int size() {
+ public int size() {
return index.size();
}
- public synchronized boolean isEmpty() {
+ public boolean isEmpty() {
return index.isEmpty();
}
diff --git a/source/net/yacy/kelondro/util/ByteArray.java b/source/net/yacy/kelondro/util/ByteArray.java
index 990e433ca..a02557d1e 100644
--- a/source/net/yacy/kelondro/util/ByteArray.java
+++ b/source/net/yacy/kelondro/util/ByteArray.java
@@ -71,11 +71,13 @@ public class ByteArray {
}
public int compareTo(final ByteArray b, final ByteOrder order) {
- return order.compare(this.buffer, 0, this.buffer.length, b.buffer, 0, b.buffer.length);
+ assert this.buffer.length == b.buffer.length;
+ return order.compare(this.buffer, b.buffer);
}
public int compareTo(final int aoffset, final int alength, final ByteArray b, final int boffset, final int blength, final ByteOrder order) {
- return order.compare(this.buffer, aoffset, alength, b.buffer, boffset, blength);
+ assert alength == blength;
+ return order.compare(this.buffer, aoffset, b.buffer, boffset, blength);
}
public int hashCode() {