Skip to content

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

loading paths now share 256 fixed locks, eliminating per-host lock accumulation and the lock-creation race

Michael Peter Christenc2c7783be84e
diff --git a/source/net/yacy/crawler/robots/RobotsTxt.java b/source/net/yacy/crawler/robots/RobotsTxt.java
index 0bc5a3928..38c0a8dc0 100644
--- a/source/net/yacy/crawler/robots/RobotsTxt.java
+++ b/source/net/yacy/crawler/robots/RobotsTxt.java
@@ -35,8 +35,6 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
@@ -67,17 +65,14 @@ public class RobotsTxt {
protected static final String ROBOTS_DB_PATH_SEPARATOR = ";";
protected static final Pattern ROBOTS_DB_PATH_SEPARATOR_MATCHER = Pattern.compile(ROBOTS_DB_PATH_SEPARATOR);
- private final ConcurrentMap<String, DomSync> syncObjects;
+ /** Fixed lock stripes bound memory use; colliding hosts serialize robots.txt fetches. */
+ private final Object[] syncObjects = new Object[256];
//private static final HashSet<String> loadedRobots = new HashSet<String>(); // only for debugging
private final WorkTables tables;
private final LoaderDispatcher loader;
/** Thread pool used to launch concurrent tasks */
private final ThreadPoolExecutor threadPool;
- private static class DomSync {
- private DomSync() {}
- }
-
/**
*
* @param worktables
@@ -89,7 +84,9 @@ public class RobotsTxt {
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(),
new NamePrefixThreadFactory(RobotsTxt.class.getSimpleName()));
- this.syncObjects = new ConcurrentHashMap<>();
+ for (int i = 0; i < this.syncObjects.length; i++) {
+ this.syncObjects[i] = new Object();
+ }
this.tables = worktables;
this.loader = loader;
try {
@@ -106,7 +103,11 @@ public class RobotsTxt {
public void clear() throws IOException {
log.info("clearing robots table");
this.tables.getHeap(WorkTables.TABLE_ROBOTS_NAME).clear();
- this.syncObjects.clear();
+ }
+
+ /** Both loading paths must use the same stable lock for a host and port. */
+ private Object lockForHost(final String hostPort) {
+ return this.syncObjects[hostPort.hashCode() & (this.syncObjects.length - 1)];
}
public void close() {
@@ -153,15 +154,7 @@ public class RobotsTxt {
System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000 */
)) {
- // make or get a synchronization object
- DomSync syncObj = this.syncObjects.get(urlHostPort);
- if (syncObj == null) {
- syncObj = new DomSync();
- this.syncObjects.put(urlHostPort, syncObj);
- }
-
- // we can now synchronize for each host separately
- synchronized (syncObj) {
+ synchronized (lockForHost(urlHostPort)) {
// if we have not found any data or the data is older than 7 days, we need to load it from the remote server
// check the robots table again for all threads that come here because they waited for another one
// to complete a download
@@ -240,14 +233,7 @@ public class RobotsTxt {
final Thread t = new Thread("Robots.txt:ensureExist(" + theURL.toNormalform(true) + ")") {
@Override
public void run(){
- // make or get a synchronization object
- DomSync syncObj = RobotsTxt.this.syncObjects.get(urlHostPort);
- if (syncObj == null) {
- syncObj = new DomSync();
- RobotsTxt.this.syncObjects.put(urlHostPort, syncObj);
- }
- // we can now synchronize for each host separately
- synchronized (syncObj) {
+ synchronized (RobotsTxt.this.lockForHost(urlHostPort)) {
if (robotsTable.containsKey(robotsTable.encodedKey(urlHostPort))) return;
// generating the proper url to download the robots txt
diff --git a/test/java/net/yacy/crawler/robots/RobotsTxtTest.java b/test/java/net/yacy/crawler/robots/RobotsTxtTest.java
new file mode 100644
index 000000000..8def90deb
--- /dev/null
+++ b/test/java/net/yacy/crawler/robots/RobotsTxtTest.java
@@ -0,0 +1,118 @@
+package net.yacy.crawler.robots;
+
+import static org.junit.Assert.*;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.IdentityHashMap;
+import java.util.Set;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import net.yacy.cora.document.id.DigestURL;
+import net.yacy.cora.protocol.ClientIdentification;
+import net.yacy.data.WorkTables;
+import net.yacy.kelondro.blob.BEncodedHeap;
+
+public class RobotsTxtTest {
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private WorkTables tables;
+ private RobotsTxt robots;
+ private Method lockForHost;
+
+ @Before
+ public void setUp() throws Exception {
+ this.tables = new WorkTables(this.temporaryFolder.newFolder());
+ // No loader: the database recheck must avoid any network access.
+ this.robots = new RobotsTxt(this.tables, null, 2);
+ this.lockForHost = RobotsTxt.class.getDeclaredMethod("lockForHost", String.class);
+ this.lockForHost.setAccessible(true);
+ }
+
+ @After
+ public void tearDown() {
+ this.robots.close();
+ this.tables.close();
+ }
+
+ private Object lock(final String hostPort) throws Exception {
+ return this.lockForHost.invoke(this.robots, hostPort);
+ }
+
+ @Test
+ public void lockStorageStaysBoundedAndStableAcrossClear() throws Exception {
+ final Set<Object> locks = Collections.newSetFromMap(new IdentityHashMap<>());
+ final Object first = lock("example.org:443");
+ for (int i = 0; i < 100000; i++) {
+ locks.add(lock("host" + i + ".example:443"));
+ }
+ assertEquals(256, locks.size());
+ assertSame(first, lock(new String("example.org:443")));
+ // Exercise negative hashes, including the value Math.abs cannot make positive.
+ assertEquals(Integer.MIN_VALUE, "polygenelubricants".hashCode());
+ assertNotNull(lock("polygenelubricants"));
+ this.robots.clear();
+ assertSame(first, lock("example.org:443"));
+ for (int i = 0; i < 100000; i++) {
+ assertTrue(locks.contains(lock("host" + i + ".example:443")));
+ }
+ }
+
+ @Test
+ public void getEntryWaitsAndRechecksDatabase() throws Exception {
+ assertWaitsAndRechecksDatabase(false);
+ }
+
+ @Test
+ public void ensureExistWaitsAndRechecksDatabase() throws Exception {
+ assertWaitsAndRechecksDatabase(true);
+ }
+
+ private void assertWaitsAndRechecksDatabase(final boolean ensureExist) throws Exception {
+ // A public numeric address avoids DNS lookups in ensureExist's locality check.
+ final DigestURL url = new DigestURL("http://8.8.8.8/page");
+ final String hostPort = RobotsTxt.getHostPort(url);
+ final FutureTask<Void> task = new FutureTask<>(() -> {
+ if (ensureExist) {
+ this.robots.ensureExist(url, ClientIdentification.yacyInternetCrawlerAgent, false);
+ } else {
+ assertNotNull(this.robots.getEntry(url, ClientIdentification.yacyInternetCrawlerAgent));
+ }
+ return null;
+ });
+ final Thread worker = new Thread(task, "robots-lock-test");
+ try {
+ synchronized (lock(hostPort)) {
+ worker.start();
+ final long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
+ while (worker.getState() != Thread.State.BLOCKED && !task.isDone()
+ && System.nanoTime() < deadline) {
+ Thread.sleep(10);
+ }
+ assertEquals("The fetch must wait on the shared host lock",
+ Thread.State.BLOCKED, worker.getState());
+ final RobotsTxtEntry entry = new RobotsTxtEntry(
+ new DigestURL("http://8.8.8.8/robots.txt"), new ArrayList<>(),
+ new ArrayList<>(), new Date(), new Date(), null, null, 0, null);
+ final BEncodedHeap heap = this.tables.getHeap(WorkTables.TABLE_ROBOTS_NAME);
+ heap.insert(heap.encodedKey(entry.getHostName()), entry.getMem());
+ }
+ task.get(5, TimeUnit.SECONDS);
+ assertEquals(1, this.robots.size());
+ } finally {
+ worker.interrupt();
+ worker.join(5000);
+ }
+ }
+}