
Hello,我是小兔大白糖。 这篇整理面试口述与高频追问要点,方便对照站内同主题通识文。
优先级 1:岗位核心考察
方向:Java 高并发 / 分布式架构 / 低延迟系统 / 系统设计
每题结构:问题 → 核心知识点 → 高分回答要点 → 推荐回答话术(英文)
一、Java 核心 (Q1-Q8)
Q1: Explain the difference between synchronized and ReentrantLock. When would you use each?
核心知识点:锁实现、可中断、公平性、条件变量、性能差异
高分要点:
- synchronized = JVM monitor,自动释放,不可中断
- ReentrantLock = AQS 实现,必须 finally unlock,可中断/可超时/可公平
- 性能在 JDK 6+ 后相当(锁升级后)
- 选 ReentrantLock 场景:需要 tryLock 超时、需要 Condition 多条件、需要公平锁
推荐回答:
"Synchronized is the JVM built-in lock — it's simple, automatically releases
on block exit or exception, but you can't interrupt a thread waiting for it
and you can't timeout.
ReentrantLock gives you more control: tryLock with timeout, lockInterruptibly,
fair mode, and multiple Condition objects for producer-consumer scenarios.
Before JDK 6, ReentrantLock was faster. Since then, synchronized has lock
escalation (biased → lightweight → heavyweight) so performance is comparable.
My rule: default to synchronized for simplicity. Reach for ReentrantLock only
when I need timeout, interruptibility, or multiple conditions — which is
usually in complex producer-consumer or resource management code."
Q2: How does a ThreadPoolExecutor work? How do you choose core pool size, max pool size, and queue type?
核心知识点:线程池生命周期、参数选择、拒绝策略、四种队列对比
高分要点:
- 核心线程 = 常驻,最大线程 = 瞬时可扩容上限
- 有界队列保护系统,无界队列可能导致 OOM
- 拒绝策略:CallerRunsPolicy(推荐,背压)、AbortPolicy(默认抛异常)
- 公式:CPU密集型=N+1,IO密集型=2N(但要用实际压测验证)
ThreadPoolExecutor pool = new ThreadPoolExecutor(
8, // corePoolSize
16, // maximumPoolSize
60, TimeUnit.SECONDS, // keepAlive
new LinkedBlockingQueue<>(1000), // bounded queue → backpressure
new ThreadPoolExecutor.CallerRunsPolicy() // caller runs on overload
);推荐回答:
"A ThreadPoolExecutor has a lifecycle: when a task is submitted, if there are
fewer than corePoolSize threads running, it creates a new thread. If all core
threads are busy, the task goes to the work queue. If the queue is full AND
fewer than maxPoolSize threads exist, it creates an additional thread.
Most important rule: NEVER use unbounded queues with Executors.newFixedThreadPool
or newCachedThreadPool. It WILL OOM under high load. Always use bounded queues.
For a trading system, I'd choose:
- corePoolSize = CPUs for CPU-bound tasks
- A bounded LinkedBlockingQueue for backpressure
- CallerRunsPolicy as rejection handler — it slows down the producer instead
of silently dropping tasks, which is critical for financial systems"
Q3: How do you avoid GC pauses in a latency-sensitive trading system?
核心知识点:GC 选择、对象分配优化、堆外内存
高分要点:
- 选 ZGC/Shenandoah(<1ms STW,4TB 以下选 G1)
- 避免在热路径上创建对象(对象池、基本类型代替包装类)
- 堆外内存(DirectByteBuffer)绕开 GC
- -XX:+DisableExplicitGC 禁止 System.gc()
推荐回答:
"For latency-sensitive systems, the goal is to keep GC pauses under 1ms.
Three layers:
1. GC choice: ZGC or Shenandoah — both have sub-millisecond STW pauses
regardless of heap size. G1 is good for <4TB heaps with predictable pauses.
2. Object allocation discipline on the hot path:
- Use primitive types instead of boxed (long not Long)
- Pre-allocate and reuse objects via object pools (RingBuffer slots)
- Avoid string concatenation and auto-boxing in the order processing path
3. Off-heap memory: DirectByteBuffer or Unsafe for large, long-lived data
structures that would otherwise trigger GC.
The LMAX Disruptor pattern is a great example — a pre-allocated ring buffer
with no allocation on the hot path. I've used this approach for market data
distribution with zero GC in the critical code path."
Q4: What is the Disruptor pattern and why is it used in trading systems?
核心知识点:RingBuffer、无锁、伪共享、Sequence Barrier
高分要点:
- 预分配对象 → 无 GC
- CAS 代替锁 → 高并发
- Padding 避免伪共享 → 缓存行友好
- 单生产者顺序写 → 无锁争用
推荐回答:
"The LMAX Disruptor is a high-performance inter-thread messaging library built
on a pre-allocated ring buffer. It's widely used in trading systems because:
1. Zero allocation on the hot path — slots are pre-allocated, so no GC
2. Lock-free using CAS and memory barriers instead of synchronized blocks
3. Cache-line padding to avoid false sharing between producer and consumer
4. Batching — consumer can process multiple events in one claim, amortizing cost
In a trading context, I'd use it for:
- Market data fan-out: matching engine writes ticks → Disruptor → multiple
consumers (WebSocket gateways, strategy engines, risk monitors) read in parallel
- Order processing pipeline: pre-trade check → matching → post-trade settlement
The key insight is that the ring buffer imposes backpressure naturally:
if consumers are slow, the ring fills up and the producer blocks automatically."
Q5: What are the volatile and CAS semantics in Java? Where does CAS not work?
核心知识点:可见性、指令重排、ABA 问题、自旋消耗
高分要点:
- volatile:保证可见性 + 有序性,不保证原子性
- CAS:Compare-And-Swap,乐观锁,无 STW
- CAS 失败 → 自旋重试 → 高竞争下 CPU 浪费 → LongAdder 分段累加
- ABA 问题 → AtomicStampedReference
推荐回答:
"volatile guarantees visibility — a write by one thread is immediately seen
by others because it forces a store barrier to flush to main memory. It also
prevents instruction reordering around the variable. But it does NOT make
compound operations atomic — i++ is still a read-modify-write, not atomic.
CAS (Compare-And-Swap) provides atomic update without locks. It works by
comparing the current value with an expected value and only swapping if they
match — all in a single CPU instruction (cmpxchg).
CAS fails under high contention: threads spin, wasting CPU. For counters under
heavy contention, I use LongAdder which segments the counter into multiple cells.
ABA problem: between CAS read and write, the value changed from A to B back to A.
CAS sees A and proceeds, missing the intermediate change. Use AtomicStampedReference
to embed a version number for this case."
Q6: Explain the JVM memory model. What goes in each space?
核心知识点:堆结构、元空间、直接内存、GC 分区
高分要点:
┌──── Heap ─────────────────────────────┐
│ ┌── Young ──┐ ┌── Old (Tenured) ──┐ │
│ │ Eden│S0│S1│ │ │ │
│ └──────────┘ └────────────────────┘ │
└──────────────────────────────────────┘
┌── Metaspace (native memory) ──────────┐
│ Class metadata, method data │
└──────────────────────────────────────┘
┌── Direct Memory (native) ─────────────┐
│ NIO ByteBuffers │
└──────────────────────────────────────┘
推荐回答:
"The JVM memory is split into heap and non-heap areas.
Heap:
- Young Generation (Eden + two Survivor spaces S0/S1): new objects. Minor GC
happens here — copies surviving objects between survivor spaces and eventually
promotes long-lived objects to Old.
- Old Generation: long-lived objects. Full GC here is expensive.
Tuning: -Xms -Xmx set heap size, -XX:NewRatio sets young/old ratio.
Non-heap:
- Metaspace: class metadata stored in native memory (replaced PermGen in Java 8).
Tuning: -XX:MaxMetaspaceSize
- Direct Memory: NIO ByteBuffer.allocateDirect(). Bypasses heap and GC entirely.
Critical for low-latency systems — but you manage it yourself.
Key insight for trading: allocating objects in the hot path causes GC pressure.
Use direct memory or pre-allocated buffers for market data processing."
Q7: How do you troubleshoot a thread pool where tasks keep timing out?
核心知识点:排查方法、工具、根因分析
高分要点:
- 监控指标:活跃线程数、队列积压、任务等待时间、拒绝次数
- 工具:Arthas thread 命令、jstack、Micrometer 指标
- 根因分类:线程不够 / 任务本身变慢 / 下游阻塞
推荐回答:
"I'd approach this in three steps:
1. Observe: Check metrics — active threads vs pool size, queue depth, task
completion time distribution (P50/P99). If active threads = max pool size
AND queue is backing up, the pool is undersized or tasks are blocking.
2. Diagnose with Arthas:
- 'thread -n 5' to find top CPU-consuming threads
- 'thread --state BLOCKED' to find threads stuck on locks
- 'thread --state WAITING' to find threads waiting on I/O or conditions
This tells me whether tasks are blocking on external calls (Redis, DB, RPC)
or competing for an internal lock.
3. Root cause fix:
- If blocking on external calls: add timeout to the call
- If tasks are CPU-heavy: increase core pool size or optimize the task
- If queue is backing up: check if downstream (e.g., DB connection pool) is
the real bottleneck — thread pool is often a symptom, not the cause
I've used exactly this approach to track down a thread leak where
50K threads were in WAITING state — Arthas showed they were all from
a ResponseCache component that was being instantiated per-request
instead of as a singleton."
Q8: Compare ConcurrentHashMap and HashMap + synchronized. Why is ConcurrentHashMap faster?
核心知识点:分段锁、CAS、读无锁
JDK 7 vs JDK 8:
- JDK 7: Segment 分段锁(默认 16 段)——16 个并发
- JDK 8: 抛弃 Segment → 每个 bin(链表头)加 synchronized + CAS → 锁粒度到单桶
推荐回答:
"ConcurrentHashMap is faster because it minimizes lock contention through
granular locking:
JDK 7: Used segment-level locking — the map was divided into 16 segments,
each with its own ReentrantLock. Two threads writing to different segments
don't block each other. But all 16 segments share the lock pool.
JDK 8: Replaced segments with per-bucket locking using synchronized on the
first node of each hash bin, combined with CAS for insertions into empty bins.
This means:
- Reads are lock-free (volatile reads)
- Writes only lock the specific hash bucket being modified
- Resize operations are cooperative — multiple threads help with migration
For a trading system, ConcurrentHashMap is the default choice for any
shared in-memory data structure (order book cache, position tracker, etc.)
because reads have zero lock overhead."
二、分布式架构 (Q9-Q14)
Q9: How do you ensure exactly-once processing in a distributed trading system?
核心知识点:幂等性、事务消息、去重表
高分要点:
- 通过 idempotency key + DB 去重实现 exactly-once 语义
- Kafka: idempotent producer + consumer dedup
- 金融场景:DB 唯一键 = 最终保底
推荐回答:
"True exactly-once is impossible in a distributed system (FLP result).
What we implement is effectively-once using idempotency:
1. Producer: assign a unique idempotency key (order ID, event sequence number)
→ Kafka idempotent producer deduplicates by PID + sequence number
→ RocketMQ: the broker deduplicates by message key
2. Consumer: maintain a dedup table in the database
→ CREATE TABLE consumed_messages (msg_id VARCHAR PRIMARY KEY, consumed_at TIMESTAMP)
→ Before processing: INSERT INTO consumed_messages VALUES (msg_id)
→ Success: first time processing → proceed
→ DuplicateKeyException: already processed → skip (idempotent)
3. Fallback: the DB unique constraint IS the ultimate dedup guarantee.
Even if Redis SETNX fails or the dedup cache expires, the DB primary key
prevents double-processing.
For order processing specifically, the order ID is naturally unique,
so the order table itself serves as the dedup mechanism."
Q10: Design a circuit breaker for a strategy engine that places orders. How to fail safely?
核心知识点:熔断器状态机、半开探测、快速失败
高分要点:
状态机:CLOSED → (errors > threshold) → OPEN → (timeout) → HALF-OPEN
↑ │
└──── (success) ←──────┘ (failure) └──→ OPEN
策略引擎专用熔断维度:
- 策略级别:单策略熔断(盈亏超限、下单频率异常)
- 账户级别:单账户总仓位熔断
- 全局级别:交易所连接断开 → 全部策略暂停
推荐回答:
"A circuit breaker for a strategy engine has three states and three levels:
Per-strategy breaker:
→ If a strategy loses $X in Y minutes → flip to OPEN
→ All subsequent order requests from this strategy are immediately rejected
(nanosecond fast — just check a boolean flag in memory)
→ After cooling period (e.g., 5 min), transition to HALF-OPEN
→ Allow one small order through → if OK, close breaker; if not, re-open
Per-account breaker:
→ Monitor total position across all strategies on the same account
→ If net position exceeds risk limit → suspend ALL strategies on that account
Global breaker (kill switch):
→ If exchange connectivity fails or latency exceeds threshold
→ Emergency STOP: cancel all open orders, reject all new orders
→ Manual intervention required to resume
Critical design: the breaker check must be on the order hot path.
I use in-memory boolean flags updated atomically — no database lookup,
no cache call. Open/close latency must be measured in microseconds."
Q11: Redis cache breakdown, penetration, and avalanche — how to handle in a trading system?
核心知识点:缓存三大问题、解决方案
| 问题 | 场景 | 方案 |
|---|---|---|
| 穿透 | 查询不存在的数据 | Bloom Filter 预过滤 |
| 击穿 | 热点 key 过期瞬间大量请求 | 互斥锁 + 逻辑过期 |
| 雪崩 | 大量 key 同时过期 | TTL + 随机抖动 |
推荐回答:
"Three distinct problems, three distinct solutions:
Cache Penetration (querying data that doesn't exist):
→ Attacker queries non-existent instrument → every request hits DB
→ Solution: Bloom Filter pre-check. If filter says 'definitely not exists',
return immediately. If 'possibly exists', then check cache/DB.
→ For trading: pre-load all valid instruments into a local Bloom Filter.
Cache Breakdown (hot key expiry):
→ BTC order book cache expires → thousands of requests hit DB simultaneously
→ Solution: 'never expire' pattern. Set physical TTL but keep a logical
expiry timestamp in the value. Background thread refreshes before logical
expiry. On cache miss, use a distributed lock so only ONE thread penetrates.
Cache Avalanche (many keys expire simultaneously):
→ Solution: add random jitter to TTL (e.g., 300s + random(0,60))
→ For trading: order book snapshots for different instruments should have
staggered refresh times, not all refreshing at minute boundaries."
Q12: Kafka vs RocketMQ — which would you choose for order events and why?
核心知识点:事务消息、延迟消息、顺序性、适用场景
高分要点:
| 场景 | 选型 | 理由 |
|---|---|---|
| 订单事件流 | RocketMQ | 事务消息保证"本地事务+消息发送"原子 |
| 行情数据管道 | Kafka | 百万 TPS 吞吐,顺序 IO |
| 策略信号通知 | RocketMQ | 低延迟、优先级消息 |
| 审计日志 | Kafka | 大量、容忍秒级延迟 |
推荐回答:
"Both have their place in a trading system:
For ORDER EVENTS — I'd choose RocketMQ:
→ Transactional messages: order creation + MQ send in one atomic operation.
If the DB write succeeds but MQ send fails, the half-message + broker
callback mechanism ensures consistency.
→ Lower latency: RocketMQ's push model and simpler architecture give
single-digit-millisecond end-to-end latency.
For MARKET DATA — I'd use Kafka:
→ Higher throughput: sequential disk I/O + zero-copy → millions of messages/sec
→ Better for streaming/ETL: market data → Kafka → Flink → analytics
For a strategy engine, I'd use RocketMQ for order events (need transactional
guarantees) and Kafka for market data distribution (need throughput).
If the team only has one MQ, I'd lean RocketMQ for trading because correctness
(transactional messaging) matters more than raw throughput."
Q13: How do you implement a distributed lock for a trading scenario?
核心知识点:Redis Redlock、ZooKeeper、etcd
高分要点:
- Redis SET NX EX(单实例简单,非 CP)
- Redlock(多实例,CP 妥协,有争议)
- ZooKeeper 临时顺序节点(CP,但运维重)
- 锁续期:watchdog 自动续期
推荐回答:
"For a trading system, I'd use Redis with the following pattern:
Lock: SET order:lock:123 unique_value NX EX 30
→ NX = only if not exists, EX 30 = auto-expire in 30 seconds
→ unique_value = UUID to prevent accidentally releasing another's lock
Unlock (Lua script, atomic):
if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
end
Watchdog: background thread renews the lock every 10 seconds if the business
logic is still running. This prevents the lock expiring during long operations.
Why not Redlock? Martin Kleppmann's analysis showed Redlock has safety issues
under network partitions. For trading, if I need CP guarantees, I'd use
ZooKeeper's ephemeral sequential nodes with session-based locking instead.
But honestly: for most trading scenarios, a well-implemented Redis lock with
watchdog is sufficient. The key risk isn't the lock implementation — it's
the split-brain scenario where two instances think they hold the lock because
GC paused one of them beyond the lock TTL."
Q14: API rate limiting design — how to handle a market maker that floods your gateway?
核心知识点:令牌桶、滑动窗口、分级限流
高分要点:
- 单用户限流 + 全局限流 双重保护
- 令牌桶算法(允许突发,平均限流)
- 越限返回 429 + Retry-After header
推荐回答:
"I'd implement a two-tier rate limiter using the token bucket algorithm:
Tier 1 — Per-account limiter:
→ Each market maker has a rate limit defined in their SLA
→ Token bucket: tokens refill at R tokens/second, bucket capacity C
→ This allows bursts up to C while averaging R
Tier 2 — Global gateway limiter:
→ Total capacity across all accounts
→ Prevents one misbehaving client from starving others
→ If global limit is 100K RPS and account A uses 90K, account B can only
use the remaining 10K regardless of their individual limit
Implementation:
→ In-memory token buckets per account (Redis for accuracy, local for speed)
→ Check at the gateway filter level, BEFORE the request reaches business logic
→ Return HTTP 429 with Retry-After header when throttled
For ultra-low-latency scenarios, use in-memory counters with periodic sync to
Redis instead of calling Redis on every request — the 100ms sync delay is
acceptable for rate limiting accuracy vs the microseconds saved per request."
三、系统设计 (Q15-Q18)
Q15: Design a high-throughput, low-latency order processing system
核心知识点:撮合引擎、订单簿数据结构、Disruptor、风控网关
提示答题框架:接口 → 数据模型 → 核心链路 → 性能优化 → 容灾
推荐回答:
"Architecture layers:
1. API Gateway (Netty-based, async non-blocking):
→ Accepts orders via REST/WebSocket/FIX protocol
→ Rate limiting & authentication at the edge
→ Passes to pre-trade risk check
2. Pre-Trade Risk Gateway (in-memory, <100μs):
→ Validates: order size, price reasonability, position limits
→ Uses in-memory rule cache with hot-reload
→ Rejects immediately on any violation
3. Order Matching Engine (core):
→ Order book: ConcurrentSkipListMap (price-sorted) for bids/asks
→ Price-time priority: lowest ask + earliest timestamp matches first
→ Disruptor ring buffer for matching events
→ Output: match events → post-trade processing + market data broadcast
4. Post-Trade Pipeline:
→ Trade settlement → position update → P&L calculation
→ Fee calculation (maker/taker differentiated)
→ Market data delta broadcast via Disruptor → WebSocket gateways
Performance targets:
→ End-to-end: order acceptance to match < 1ms P99
→ Throughput: 100K+ orders/second per matching engine instance
→ GC: ZGC with <1ms pause target
Resilience:
→ Primary-standby matching engine with Raft-based log replication
→ If primary fails, standby takes over with < 1 second gap
→ All orders persisted to WAL before match confirmation"
Q16: Design a real-time position & P&L monitoring system for market makers
核心知识点:事件驱动、CDC、时序数据、WebSocket 推送
推荐回答:
"Data flow:
1. Trade event ingestion:
→ Every match (trade) is an event published to a high-throughput MQ (Kafka)
→ Each trade event contains: account, instrument, side, price, qty, timestamp
2. Position aggregation (stream processing):
→ Kafka → Flink/Kafka Streams → maintain running position per account+instrument
→ Keyed by (account_id, instrument) for consistent state
→ Output: position snapshot every time it changes
3. P&L calculation:
→ Realized P&L: SUM(trade_profit) = SUM(trade_qty * (price - avg_entry))
→ Unrealized P&L: current_position * (mark_price - avg_entry_price)
→ Mark price = last traded price OR index price from oracle
4. Distribution to frontend:
→ Position/P&L snapshots → Redis sorted set (keyed by account, TTL 1s)
→ Market makers subscribe via WebSocket for real-time push
→ Frontend dashboard updates on every position change
Alerting:
→ If P&L drops below threshold → trigger alert + optional auto-suspend
→ Use sliding window: 'loss > $10K in last 5 minutes' not just absolute"
Q17: Design a market data distribution system (order book broadcast)
核心知识点:增量推送、序列号、snapshot+delta、Disruptor
推荐回答:
"Design:
1. Data source: Matching engine
→ Emits order book deltas: {seq: 1001, side: BID, price: 50000, qty: 2.5}
→ Not full order book — only the changed price level
2. Fan-out: Disruptor Ring Buffer
→ Single producer (matching engine) → 3 consumer groups in parallel:
a) Public WebSocket gateways (for retail traders)
b) Institutional FIX/API gateways (for market makers)
c) Strategy engine feed (for automated strategies)
3. Delta encoding:
→ SBE (Simple Binary Encoding) instead of JSON
→ Payload per tick: ~30 bytes (vs ~200 bytes JSON)
4. Snapshot + Delta model:
→ New connection → send full order book snapshot (all levels)
→ Subsequent updates: send only deltas with monotonically increasing seq
→ Client tracks last seen seq → on reconnect, send 'replay from seq N'
→ Server maintains ring buffer of last 10,000 deltas for replay
→ If client falls behind > 10K → force full snapshot
5. Slow consumer handling:
→ If client TCP buffer is full → throttle or disconnect
→ Never let one slow client block the broadcast
Performance:
→ Matching engine tick → last WebSocket subscriber: < 1ms P99
→ 500K messages/second through the ring buffer
→ GC-free on the hot path (pre-allocated objects in ring buffer)"
Q18: Design a fault-tolerant configuration service for strategy parameters
核心知识点:热更新、版本管理、灰度发布、回滚
推荐回答:
"Requirements:
→ Hot-reload: parameter changes take effect without restart
→ Audit: who changed what, when
→ Rollback: one-click revert to previous version
→ Guardrails: parameter validation before acceptance
Architecture:
1. Storage:
→ PostgreSQL for persistence (ACID for audit trail)
→ Redis for hot path reads (strategies read config from Redis, not DB)
→ Config push via Redis Pub/Sub: when config changes → publish event
→ strategy instances subscribe → reload from Redis
2. API for traders:
→ PUT /strategies/{id}/params → validate → write DB → update Redis → publish
→ GET /strategies/{id}/params/history → list all versions
→ POST /strategies/{id}/params/rollback → revert to version N
3. Validation gateway:
→ Parameter range check before persistence
→ e.g., 'spread_pct' must be between 0.01 and 5.0
→ e.g., 'order_size' * 'max_position' < account_balance * leverage
→ Reject invalid at API level, not in strategy execution
4. Canary deployment for config:
→ Roll out to 10% of strategies first → monitor for 5 min
→ If P&L, error rate, latency all OK → roll to 100%
→ If anomaly detected → auto-rollback
This is conceptually similar to what I built for 某业务's meltdown
configuration system — Redis Pub/Sub for instant propagation, with
fallback to polling if Pub/Sub fails."
四、算法题 (Q19-Q20)
Q19: Implement a thread-safe LRU cache
高频程度:⭐⭐⭐⭐⭐
核心知识点:HashMap + 双向链表、并发安全
class LRUCache<K, V> {
private final int capacity;
private final Map<K, Node> map;
private final Node head, tail; // dummy nodes
private static class Node<K, V> {
K key; V value; Node prev, next;
}
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new ConcurrentHashMap<>();
head = new Node(); tail = new Node();
head.next = tail; tail.prev = head;
}
public V get(K key) {
Node<K, V> node = map.get(key);
if (node == null) return null;
synchronized (this) {
moveToHead(node);
}
return node.value;
}
public void put(K key, V value) {
Node<K, V> node = map.get(key);
synchronized (this) {
if (node != null) {
node.value = value;
moveToHead(node);
} else {
node = new Node<>(key, value);
map.put(key, node);
addToHead(node);
if (map.size() > capacity) {
Node removed = removeTail();
map.remove(removed.key);
}
}
}
}
}推荐回答:
"An LRU cache combines a HashMap for O(1) lookup with a doubly-linked list
for O(1) eviction. The HashMap maps keys to list nodes. On access: move the
node to the head. On eviction: remove the tail node.
For thread safety, I synchronize only the list operations — the ConcurrentHashMap
already handles concurrent reads. This gives good throughput for read-heavy
workloads.
Tradeoff: this implementation synchronizes on 'this'. For higher concurrency,
you could use per-segment locking or a ConcurrentLinkedHashMap. But for most
use cases, the simpler approach is sufficient and less bug-prone."
Q20: Top K frequent elements in a stream (Heap + HashMap)
public List<Integer> topKFrequent(int[] nums, int k) {
// Count frequencies
Map<Integer, Integer> freq = new HashMap<>();
for (int n : nums) freq.merge(n, 1, Integer::sum);
// Min-heap of size K
PriorityQueue<Integer> heap = new PriorityQueue<>(
Comparator.comparingInt(freq::get));
for (int n : freq.keySet()) {
heap.offer(n);
if (heap.size() > k) heap.poll();
}
return new ArrayList<>(heap);
}
// Time: O(N log K), Space: O(N)推荐回答: "Count with HashMap (O(N)), then maintain a min-heap of size K (O(N log K)). If K is small, this is efficient. For trading system analogy: this is like finding the top K most traded instruments in real-time — you'd use a similar heap-based approach with a time-decaying counter."
速度检查
| 模块 | 题数 | 状态 |
|---|---|---|
| Java 核心 | 8 (Q1-Q8) | ✅ |
| 分布式架构 | 6 (Q9-Q14) | ✅ |
| 系统设计 | 4 (Q15-Q18) | ✅ |
| 算法题 | 2 (Q19-Q20) | ✅ |
没有 LeetCode 原题集? 熟练 LRU、TopK、买卖股票(1/2)、岛屿数量、二叉树层序遍历,后端岗够用。重点是系统设计不在算法。