Multithreaded Web Crawler
MediumConcurrencyThread PoolConcurrentHashMapBFSProducer-ConsumerExecutorService
Problem Statement
Implement a multithreaded web crawler that crawls all URLs reachable from a startUrl, visiting only URLs that share the same hostname. The HtmlParser.getUrls(url) interface returns all hyperlinks on a given page (simulating an HTTP GET + parse). A single-threaded implementation will exceed time limits.
interface HtmlParser {
List<String> getUrls(String url);
}
class Solution {
public List<String> crawl(String startUrl, HtmlParser htmlParser) {}
}
Key Entities
- ExecutorService / ThreadPoolExecutor: Manages worker threads fetching pages in parallel.
- ConcurrentHashMap / ConcurrentHashSet: Tracks visited URLs to avoid duplicates.
- BlockingQueue: Work queue feeding URLs to worker threads (BFS frontier).
- CountDownLatch / Phaser: Detects when all in-flight crawl tasks have completed.
Requirements
- Only crawl URLs whose hostname matches the
startUrlhostname. - Never visit the same URL twice.
- Crawl must terminate — no infinite loops.
- Use multiple threads to parallelize
getUrls()calls. - Return all discovered same-hostname URLs.
Asked at: Facebook, Dropbox, Google, Amazon, Microsoft, Uber
!Constraints
- 1 ≤ urls.length ≤ 1000
- 1 ≤ urls[i].length ≤ 300
- startUrl is guaranteed to be in the urls list.
- No duplicate URLs exist in the input url list.
- Hostname labels: 1–63 characters, ASCII letters (a-z), digits (0-9), hyphens (not at start or end).
Output
Run or submit your code to see output here.