Java Backend Interview Topics: Thread‑Safe Collections, JVM Memory, Optimistic Lock, Caching, and More
The article reviews key Java backend interview topics—including thread‑safe collections, JVM memory layout and heap tuning, Full GC troubleshooting, Java 8 features, optimistic locking, stock‑over‑sell handling with Redis, MySQL scaling, cache‑consistency patterns, anti‑bot safeguards, and Bloom filters—while noting JD’s recent 30% salary hike for algorithm engineers.
JD recently announced a 30% salary increase for all algorithm engineers, sparking discussion about compensation trends.
JD First‑Round Interview (Java)
Thread‑Safe Collections
In the java.util package only Vector and Hashtable are thread‑safe; all other collections are not.
Vector : synchronized dynamic array, not recommended when thread safety is not required.
Hashtable : synchronized hash table, replaced by ConcurrentHashMap in most cases.
The java.util.concurrent package provides fully thread‑safe collections:
ConcurrentHashMap : segment‑locked in JDK 1.7, lock‑free per bucket in JDK 1.8.
ConcurrentSkipListMap : sorted map based on a skip‑list.
ConcurrentSkipListSet : ordered set backed by ConcurrentSkipListMap.
CopyOnWriteArraySet : thread‑safe unordered set implemented via CopyOnWriteArrayList.
CopyOnWriteArrayList : thread‑safe list that copies the underlying array on each write.
ConcurrentLinkedQueue : lock‑free high‑concurrency queue.
BlockingQueue : provides blocking semantics for producer‑consumer scenarios.
LinkedBlockingDeque and ConcurrentLinkedDeque : thread‑safe double‑ended queues.
JVM Memory Structure
The JVM runtime memory consists of the following areas (JDK 8):
Program Counter (PC) Register
Java Virtual Machine Stack
Native Method Stack
Heap (young and old generations)
Metaspace (method area)
Runtime Constant Pool
Direct Memory (off‑heap, accessed via NIO)
Setting JVM Heap Size
Use startup parameters: -Xms: initial heap size (e.g., -Xms256m) -Xmx: maximum heap size (e.g., -Xmx1024m)
Example:
java -Xms512m -Xmx2048m -jar YourApp.jarFull GC Diagnosis
Common causes of Full GC include large objects, memory leaks, long‑lived objects, Metaspace exhaustion, explicit System.gc() calls, and improper JVM flags.
Typical troubleshooting steps:
Monitor with Prometheus or jstat to view old‑generation usage and GC frequency.
Use jmap -histo to list live objects.
Dump the heap with jmap -dump:format=b,file=heap.bin.
Analyze with visual tools such as JVisualVM or MAT.
Java 8 New Features
Feature
Description
Example
Lambda Expressions
Simplify anonymous classes, enable functional programming. (a, b) -> a + b Functional Interfaces
Single‑abstract‑method interfaces, marked with @FunctionalInterface. Runnable, Comparator Stream API
Chainable operations on collections, supports parallel execution.
list.stream().filter(x -> x > 0).collect(Collectors.toList())Optional
Wrap potentially null values to avoid NPEs. Optional.ofNullable(v).orElse("default") Method References
Compact form of lambdas. System.out::println Default & Static Methods in Interfaces
Provide implementations directly in interfaces.
interface A { default void print() { System.out.println("default"); } }Parallel Array Sort
Multi‑threaded sorting. Arrays.parallelSort(array) Repeatable Annotations
Allow multiple instances of the same annotation. @Repeatable Type Annotations
Annotate any use of a type. List<@NonNull String> list CompletableFuture
Enhanced asynchronous programming.
CompletableFuture.supplyAsync(() -> "result").thenAccept(System.out::println)Optimistic Lock
Optimistic locking assumes conflicts are rare and uses compare‑and‑swap (CAS) or version numbers to detect conflicts. If a conflict occurs, the operation is retried.
CAS via java.util.concurrent.atomic classes.
Version‑field comparison.
Timestamp comparison.
Preventing Stock Over‑Sell
Typical flow:
Receive flash‑sale request and perform basic validation.
Check stock in Redis; if sufficient, decrement atomically (e.g., DECR or Lua script).
Publish a success message to a queue.
Consumer creates order, applies optimistic lock on DB stock, ensures idempotency.
Periodically reconcile Redis and DB to achieve eventual consistency.
MySQL Scaling under High Traffic
Read‑write splitting with master‑slave replication.
Sharding tables or databases to reduce per‑table load.
Introduce caching layers (e.g., Redis) with appropriate cache‑invalidation strategies.
Cache Consistency Solutions
Use a cache‑aside pattern: read‑through on miss, write‑through or write‑behind on update, and delete stale entries.
Two common approaches for reliable cache eviction:
Retry via a message queue when deletion fails.
Subscribe to MySQL binlog (e.g., using Canal) and delete cache based on change events.
Message‑queue based retry ensures eventual consistency.
Anti‑Bot Measures for Seckill
CAPTCHA or slider verification.
Rate limiting per IP, account, or device.
Bloom Filter Overview
A Bloom filter consists of a bit array initialized to 0 and multiple hash functions. Insertion sets bits to 1; query checks if all corresponding bits are 1. It provides fast membership tests with false‑positive probability but no false negatives.
Algorithm Note
LeetCode 445 – Two Sum II (sorted array).
Chat Section
Discussion about job offers and career planning.
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 Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
