Master Java Backend Interview Questions: Sets, HashMaps, Concurrency, and More
This article compiles essential Java backend interview topics, covering the differences between TreeSet and HashSet, HashMap collision handling and resizing, ConcurrentHashMap's lock strategy, thread pool creation, synchronization primitives like CountDownLatch and CyclicBarrier, database indexing, CAP theorem, idempotence, locking mechanisms, JVM GC roots, reflection, dynamic proxies, distributed locks, ThreadLocal optimization, and key considerations for designing a high‑traffic seckill system.
TreeSet vs. HashSet Differences
TreeSet is backed by a TreeMap (a red‑black tree) which provides automatic sorting using equals or compareTo. HashSet is backed by a HashMap, stores elements in an unordered fashion, and requires proper hashCode and equals implementations.
HashSet accepts a single null value, while TreeSet does not allow null and throws a NullPointerException by default.
set里没有重复数据,treeSet里连虚无都没有。
HashMap Conflict Resolution and Expansion
Internally, HashMap uses an array of buckets combined with linked lists (or red‑black trees when a bucket exceeds eight entries in Java 8+). It starts with 16 buckets.
When inserting, the object's hashCode determines the bucket; collisions are resolved via the linked list (or tree). A load factor triggers resizing to double the capacity, after which all entries are rehashed using the transfer method.
经验:resize非常耗时,所以如果能够提前预估容量,可以把initailCapacity提前固定下来。
How ConcurrentHashMap Achieves High Concurrency
It uses segmented (striped) locks, where each lock protects a portion of the map, reducing contention among threads.
这道题往深里问会死人的,篇幅有限,不啰嗦。
Typical ThreadPool Usage
For ordinary scenarios, create pools via Executors (Single, Fixed, Cached). For finer control, customize ThreadPoolExecutor, paying attention to the blocking queue and saturation policy.
他们很喜欢你提到阿里规范,这让我觉得jdk设计的很low
Synchronizing Multiple Threads at a Barrier
Classic solutions include CountDownLatch (main thread awaits, workers count down) and CyclicBarrier (threads await until a threshold is reached). Simpler APIs such as Thread.join() or Future.get() can also be used.
也可以答sleep啊。有什么问题么?我用while等待一个变量也是可以的,但我为什么要这么做?
Database Index Structures
B+ Tree – disk‑oriented index that must follow the left‑most prefix rule.
Hash – similar to HashMap, resolves collisions with linked lists.
pg的索引结构就多了去了。Mysql这么少怎么感觉怪怪的?难道要我回答存储引擎的区别?
How to Add an Index for SELECT * FROM t WHERE a=? AND b>? ORDER BY c LIMIT 0,100
The index is useful only when the ORDER BY column appears in the WHERE clause; otherwise sorting is performed.
Following the leftmost principle, create a composite index on (a,b).
Clustered vs. Non‑Clustered Indexes
A table can have only one clustered index. In InnoDB, the primary index and data share the same B+‑Tree file (leaf nodes store the actual rows). MyISAM does not support clustered indexes; its leaf nodes store pointers to the data file.
对编程来说没什么鸟用。
Understanding CAP and Redis
Consistency– consistency Availability – availability Partition tolerance – partition tolerance (trade‑off between C and A)
Redis simple master‑slave mode emphasizes CP (strong consistency). Redis Cluster follows AP, prioritizing availability.
cap就是帽子,绿油油的那种
What Is Idempotence? How to Ensure It in APIs
Idempotence means repeated executions have the same effect. Common techniques: redirect after a successful POST to avoid duplicate submissions, use serial numbers, or employ a status table to check and enforce single execution.
就如同表白,每次表白都是被拒绝,因为我就是那个id!
Optimistic vs. Pessimistic Locks
Pessimistic lock assumes the worst case; it locks data (e.g., DB row lock, Java synchronized) so other threads must wait.
Optimistic lock assumes the best case; it avoids locking but adds a validation step (e.g., CAS, version numbers).
悲观锁是老婆,有你独占;乐观锁是炮友,按预约规划
How Does the JVM Determine If an Object Is Collectible?
Objects unreachable from any GC root are considered collectible.
通常被骂“断子绝孙”的人,就是要被回收的root
GC Roots Types
1. Objects referenced from the JVM stack (local variables).
2. Objects referenced from native method stacks (JNI).
3. Objects referenced by static variables and constants in the method area.
4. Objects referenced by active threads.
所以不要让他们过度繁殖。
Can Reflection Retrieve Method Names, Parameter Names, and Types?
Yes. Since Java 8, Parameter can provide parameter names when compiled with -parameters. javac -parameters By default, this flag is disabled.
问题都偏到月球上去了
Dynamic Proxy Implementation and Differences Between Cglib and JDK Proxies
Java dynamic proxy uses InvocationHandler and Proxy to create interface‑based proxies.
Cglib generates bytecode via ASM, can proxy concrete classes (except final ones), while JDK proxies can only proxy interfaces.
在spring里,cglib胜出
Distributed Lock Implementations and Differences Between Redis and Zookeeper Locks
Two main categories: optimistic (version/CAS) and pessimistic (DB record, row lock, Redis SETNX, Zookeeper). Redis locks use polling; Zookeeper provides watch‑based notifications and can implement fair locks.
从优雅性来说,显然redis胜出
What Is ThreadLocal and How to Use It?
ThreadLocal isolates data per thread via an internal map, similar to a servlet request scope.
Typical use cases include storing per‑thread statistics or context.
据说这是一种线程同步方式,但它明显无锁啊。
ThreadLocal Optimizations
The default map has poor performance; Netty introduces FastThreadLocal by extending Thread and improving the underlying map.
搞不懂jdk,明明有O(1)的Map,非要自己造个更慢的轮子,为什么呢?
Designing a Seckill System: Key Considerations
1. Data pre‑warming – load data into cache before traffic spikes.
2. Caching – both CDN and data cache, ensure high availability.
3. Prevent overselling – use MQ to serialize stock updates or manipulate cache directly.
4. Traffic shaping – buffer requests with MQ for smooth processing.
5. Circuit breaking and rate limiting – protect core services and reject abnormal traffic.
6. Elastic scaling – add servers when load reaches limits.
怕就怕抓住一点问到底。秒杀个屁啊,淘宝的秒杀要么抢不到,要么500!
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
