China Merchants Bank Java Backend Interview: 20 Technical Questions & Answers
A developer shares their successful China Merchants Bank Java backend interview experience, detailing 20 technical questions covering HashMap, ConcurrentHashMap, synchronization, thread pools, Redis cache penetration, MySQL indexing, Spring Boot auto-configuration, Agent memory, RAG, multi-agent orchestration, and more, with answers and preparation tips.
A developer known as "Programmer Xiao Meng" shares a friend's successful interview experience at China Merchants Bank for a Java backend position with a 15k monthly salary, starting next month. The first-round interview lasted about 30 minutes, conducted online, with a friendly interviewer and no pressure tactics. Approximately 20% of the questions focused on the candidate's resume projects (which mentioned AI and Agent), while 80% covered traditional backend fundamentals across a broad range but without deep source-code diving. Notably, this round did not include a coding exercise, though the author notes that other candidates for the same role did encounter coding tests.
Interview Details
Position : Java Backend Development
Date : October 12
Format : Online
Duration : ~30 minutes
Technical Scope : Java Collections & Concurrency, Redis, MySQL, Spring Boot, RAG, Agent
Coding Test : Not encountered in this round
The question set is well-suited for checking whether a candidate can accurately explain traditional backend basics and clearly articulate the engineering implementation of AI projects.
20 Interview Questions with Reference Answers
01. HashMap and ConcurrentHashMap Implementation (JDK 8+) and Locking in ConcurrentHashMap
Start by specifying the version: base the explanation on JDK 8 and mention later version changes.
HashMap structure: array + linked list + red-black tree. Hash to locate bucket; on collision, search within bucket. When conditions are met, linked list converts to red-black tree.
Key thresholds: 8 and 64 . Treeification threshold is 8, but array capacity must reach at least 64 before treeification is considered; if capacity is small, resizing takes priority. Do not simply say "the 8th element triggers treeification"; the exact trigger depends on the insertion path. HashMap is not thread-safe.
ConcurrentHashMap (JDK 8) also uses array with bucket-level linked lists and trees, combining CAS, synchronized, and visibility mechanisms for concurrency control:
Empty bucket insertion : attempt CAS to set new node.
Non-empty bucket update : typically synchronize on the bucket's head node, re-verify it's still the head after entering the synchronized block.
Tree bins : have additional tree-node coordination mechanisms; cannot treat all internal paths as a single lock.
Reads : ordinary get usually does not acquire the monitor lock used for updates; resizing includes corresponding access and migration handling.
Common follow-up : Container thread-safety does not guarantee atomicity of multi-step business logic. For example, get then put for counting still has a race condition; use atomic update methods like compute or merge.
02. Difference Between synchronized and Lock
Compare ReentrantLock (the primary Lock implementation) with synchronized.
Usage : synchronized is a language keyword; lock management on entry/exit of synchronized region. ReentrantLock requires explicit lock/unlock method calls.
Release : synchronized releases on normal or exceptional exit from synchronized region. ReentrantLock must unlock in finally block after successful lock.
Lock Acquisition : synchronized has no timeout or interruptible acquisition API. ReentrantLock supports tryLock, timed tryLock, lockInterruptibly.
Condition Waiting : synchronized uses wait/notify monitor mechanism. ReentrantLock can create multiple Condition objects.
Fairness : synchronized has no fairness policy configuration. ReentrantLock can choose fair or non-fair mode.
Both provide mutual exclusion and memory visibility; both are reentrant. Prefer synchronized for simple, maintainable code; choose explicit locks when timeout acquisition, interruptible waiting, or multiple condition queues are needed.
lock.lock();
try {
updateInventory();
} finally {
lock.unlock();
}If using tryLock, only call unlock after confirming successful lock acquisition. Performance depends on JDK version and contention; cannot claim one is always faster.
03. Thread Pool Core Parameters
Using ThreadPoolExecutor, seven common parameters:
corePoolSize : Core thread count
maximumPoolSize : Maximum thread count
keepAliveTime : Idle thread survival time before reclamation
unit : Time unit for keepAliveTime
workQueue : Queue holding waiting tasks
threadFactory : Creates threads, often used to set names
handler : Rejection handler when task cannot be accepted
Task submission order: if core threads insufficient, create new thread; if core reached, try enqueue; if enqueue fails, expand to max threads; if still cannot accept, execute rejection policy . Also consider pool shutdown state.
Example: core=2, max=4, queue capacity=2, all tasks blocking and not yet completed. First 2 tasks get new threads, 3rd and 4th queued, 5th and 6th trigger thread expansion, 7th rejected.
Queue choice directly changes thread pool behavior. With unbounded queue, tasks keep queuing and max threads rarely come into play. Core threads are not reclaimed by default due to idle timeout; allowing core thread timeout requires extra configuration.
04. Thread Pool Rejection Policies and Business Selection
Four built-in policies:
AbortPolicy : Throws RejectedExecutionException. Default; caller must handle exception.
CallerRunsPolicy : Task executed by submitting thread. Slows down caller; tasks discarded after pool shutdown.
DiscardPolicy : Silently discards current task. No notification to caller.
DiscardOldestPolicy : Removes head of queue, retries submission. Does not terminate running threads; discards after shutdown.
For critical tasks like order or payment state changes that cannot be silently lost, prefer explicit failure with monitoring and reliable compensation over discard policies. For cross-process reliable reception and recovery, consider persistent task tables or message queues. CallerRunsPolicy provides backpressure but may block HTTP request threads or event loops; it is not a "zero-loss silver bullet".
05. Redis Cache Penetration: Definition and Solutions
Cache penetration occurs when requested data is absent in both cache and database, causing requests to bypass cache and hit the database repeatedly. Example: querying non-existent product IDs.
Common combined approaches:
Validate parameters at entry, intercept obviously illegal IDs, formats, and access patterns.
Cache short-lived null values for confirmed non-existent data, with TTL tuned to business needs.
Use Bloom filters for pre-maintained datasets to pre-filter impossible queries.
Combine authentication, rate limiting, and monitoring for abnormal traffic.
Bloom filter accuracy: given correct data insertion, "not exists" can be used to exclude; "may exist" still requires further query due to false positives. Stale filters (unsynced new data, incomplete initialization) must not block legitimate requests.
Distinguish three concepts: penetration queries non-existent data; breakdown is hot-key expiry causing simultaneous fallback; avalanche is mass cache expiry or cache service failure causing overall fallback pressure.
06. MySQL Clustered vs Non-Clustered Index Differences
Scope to InnoDB: clustered index leaf pages contain row data; secondary index leaf records contain secondary key + clustered index key (usually primary key).
Primary key lookup traverses clustered index; secondary index lookup requires fetching primary key then looking up clustered index if needed columns are not covered — this is back-table lookup (回表) .
Example: table with PK id, secondary index idx_name(name):
-- id and name present in secondary index, may use covering index
SELECT id, name FROM users WHERE name = 'Xiao Chen';
-- phone not in index, usually requires back-table lookup
SELECT id, name, phone FROM users WHERE name = 'Xiao Chen';An InnoDB table has exactly one clustered organization. Without explicit PK, a suitable unique non-null index is chosen; otherwise a hidden clustered index is used.
07. MySQL Index Failure Scenarios
Distinguish two cases: query writing prevents index utilization, and optimizer decides full scan is cheaper. Not using an expected index does not automatically mean "index is broken".
Common investigation points:
Functions or calculations on indexed column, e.g., DATE(create_time); function-based indexes or generated columns need separate analysis.
Leading wildcard on ordinary B+ tree index, e.g., LIKE '%bank', usually prevents prefix range scan.
Type mismatch causing implicit conversion on indexed column, e.g., string column compared to number.
Composite index not leveraging leftmost prefix; note that some versions/conditions have Skip Scan optimizations, so avoid stating absolute rules.
Low selectivity, many returned rows, or inaccurate statistics leading optimizer to choose other access paths.
Time queries can be rewritten as range conditions:
-- Function on column hinders index range scan
SELECT id FROM orders WHERE DATE(create_time) = '2026-10-09';
-- Better for B+ tree index range scan
SELECT id FROM orders
WHERE create_time >= '2026-10-09 00:00:00'
AND create_time < '2026-10-10 00:00:00';Common mistake: for composite index (a,b,c), condition a=1 AND b>10 AND c=3 — c usually cannot further narrow the same index scan range, but may still participate in index condition pushdown or covering access. Do not say the entire index becomes invalid after a range condition.
08. Spring Boot Auto-Configuration Implementation
Explain around "entry point, candidate configurations, condition evaluation, bean registration". @SpringBootApplication includes auto-configuration enablement; @EnableAutoConfiguration imports auto-configuration selection logic. Framework obtains candidate auto-configuration classes, then decides which configurations take effect based on classpath, existing beans, configuration properties, etc.
Common conditional annotations: @ConditionalOnClass: required class present on classpath. @ConditionalOnMissingBean: provide default only when user hasn't provided a bean. @ConditionalOnProperty: activate when property matches condition.
Version differences must be clear. Earlier versions used spring.factories to register candidates; Spring Boot 2.7 introduced AutoConfiguration.imports, and Boot 3+ uses this new mechanism. Do not answer "scan spring.factories" for all versions.
Auto-configuration does not mean unconditional bean creation, nor does it scan all classes from all jars into the container.
09. Understanding Agent Memory Module
Start with: Model calls do not inherently persist previous interactions; the application must decide what to save, what to retrieve, and what fits into the current context window.
Design can distinguish three categories:
In-session memory : Recent conversation turns, necessary tool results. Handling: sliding window, summarization, token budget.
Long-term reusable info : User-explicit preferences, task conclusions. Handling: structured storage or on-demand retrieval.
Current process state : Completed nodes, pending confirmations, retry counts. Handling: managed by process state and checkpoint mechanisms.
With Spring AI, combine ChatMemory, ChatMemoryRepository, and relevant Advisors to explain how session memory is integrated. Full chat history and the memory context fed to the model each turn should be designed separately.
Verify whether tool invocations and receipts can be fully persisted per the chosen repository and framework version; if needed, store execution traces separately.
Do not concatenate all historical messages indefinitely — context bloats and stale info may become invalid. In multi-user systems, establish authorization relationships between users, tenants, and sessions on the server side; validate ownership before reading memory to prevent cross-session leakage.
10. LLM Hallucination and RAG Mitigation in Project
Hallucination: model generates plausible but factually inconsistent content — e.g., fabricating regulations, citing non-existent documents, or stating uncertain conclusions confidently.
Focus on RAG. Expand "connected a vector store" into a complete pipeline:
Knowledge Preparation : Clean documents, chunk reasonably, retain metadata (source, version, timestamp, permissions).
Retrieval : Fetch relevant materials for the query; combine keyword and vector recall if needed, then re-rank.
Context Assembly : Select relevant evidence, control length, avoid stuffing irrelevant material into the model.
Generation Constraints : Require key conclusions to cite sources; explicitly state when evidence is insufficient; ask follow-up if needed.
Result Verification : Check if answer is supported by retrieved material, citations are real; feed failure cases into evaluation set.
RAG reduces but cannot eliminate hallucination. Materials may be outdated, retrieval may miss relevant docs, model may misread evidence. Dynamic facts like balances, real-time inventory, order status should be fetched via controlled business APIs and verified.
If asked about effectiveness, cite actual evaluation methods and real results; do not invent accuracy rates, improvement percentages, or production scale without having done the work.
11. Multi-Agent Orchestration Implementation in Project
Used Spring AI Alibaba. Explain business rationale for role decomposition, then node collaboration; illustrate with generic "problem analysis, retrieval, tool execution, result verification" flow.
Example flow: entry node clarifies question, routing node decides between retrieval branch or tool branch, each node outputs structured results, aggregation node generates answer, verification node decides continue, supplement retrieval, or terminate.
Spring AI Alibaba provides sequential, parallel, routing, Supervisor modes; complex flows can use custom Graph. In interview, clarify these implementation details:
Node responsibilities : prompts, context, tools used per node; input/output formats.
State passing : share necessary task state; roles don't need full history; identity injected from trusted context.
Branching conditions : which decisions are deterministic code vs. model-based routing.
Failure handling : node timeouts, max execution rounds, retry/exit conditions; idempotency for side-effect calls.
Recovery & observability : record execution traces; for pause/resume, persist checkpoints and track whether tools have executed.
"Used a framework" is just the start. Real project understanding shows in: why decomposed this way, how results are passed, what happens on failure.
12. Why volatile Cannot Guarantee Thread-Safe count++
volatileprovides visibility and ordering guarantees, but count++ comprises read, increment, write steps. Two threads may read same old value, causing lost updates.
For atomic counting, use AtomicInteger per semantics, or protect the full operation with a lock. LongAdder suits high-contention statistics but is not a drop-in replacement for scenarios requiring precise atomic reads.
In interview, distinguish "single read/write of a variable" from "multi-step business operation".
13. Why Spring Transaction May Not Work
First check if default proxy mode is used. Common causes: object not managed by Spring, call not going through proxy, internal self-invocation of transactional method within same object, exception caught without rethrow or marking rollback.
Default rollback rules target RuntimeException and Error; checked exceptions need rollbackFor or global rollback config. Async thread switch loses original thread-bound transaction context.
Do not memorize "non-public methods never have transactions". Method visibility, proxy type, and Spring version all affect outcome; since Spring 6, class proxy support for some non-public methods differs from older versions.
14. Online Slow SQL Troubleshooting Order
First identify the specific SQL, actual parameters, latency distribution, and execution frequency. Then examine execution plan, scanned rows, indexes, sorting, back-table lookups, lock waits. EXPLAIN analyzes plan; in controlled environments, EXPLAIN ANALYZE shows actual execution but does execute the statement, so it's not zero-cost.
Optimize by rewriting queries, adjusting composite indexes, reducing unnecessary columns, improving pagination, or addressing lock contention. After changes, retest with similar data volume and monitor write overhead from new indexes.
15. Keeping Redis and Database Consistent
Common Cache-Aside pattern: read cache, on miss query DB and populate; on update, commit DB change then invalidate corresponding cache.
This is an engineering strategy, not equivalent to strong consistency . DB commit succeeds but cache deletion fails, or read-write race causes stale value re-population — both can leave temporary inconsistency.
Combine TTL, invalidation retries, persistent events, Outbox, or CDC based on business tolerance; monitor and compensate failures. For strong constraints like balance deduction, verify within authoritative storage and transaction boundaries; do not rely solely on cached reads.
16. RAG vs Fine-Tuning: Differences and Selection
RAG retrieves external knowledge at inference time, suitable for scenarios needing up-to-date materials, source attribution, and access control. Fine-tuning adjusts model parameters, better for improving specific task behavior, style, or output habits.
They can be combined but are not universal patches. Frequent knowledge updates cannot be handled by fine-tuning alone as a real-time knowledge base; poor retrieval cannot be fixed by only changing prompts.
Before choosing, diagnose failure root cause: knowledge gaps, recall insufficiency, context organization, reasoning ability, or format/behavior instability — then decide which layer to improve.
17. Relationship Between Tool Calling and MCP
Tool Calling defines how a model expresses "which tool to call and with what parameters". Actual execution is typically performed by the host application or backend.
MCP standardizes how tools and context capabilities are discovered, invoked, and provided. Typical flow: backend discovers tools via MCP, provides descriptions to model; model produces call plan; backend validates permissions and parameters, executes via MCP, returns results.
MCP does not replace authorization checks, nor does it automatically make tool results or model answers correct. Even if the model picks the right tool, it may pass wrong business parameters.
18. Preventing Prompt Injection and Privilege Escalation in Agents
User messages, retrieved documents, and tool responses may all contain instructions attempting to alter Agent behavior. Even with RAG, prompt injection is not automatically solved.
Separate model suggestions from backend permission control: whitelist tools with least privilege; read identity from server side; validate parameters, resource ownership, and accessible scope; add confirmation steps for side-effect actions (transfers, deletions, messaging) per business rules.
Conversation memory must also prevent untrusted content from being stored long-term as "rules". Limit call counts, runtime duration, output scope; retain auditable logs.
19. Evaluating RAG and Agent Project Effectiveness
First prepare a representative evaluation set covering normal questions, unanswerable questions, ambiguous queries, outdated knowledge, and permission boundaries; then analyze failure causes by stage.
Metrics split by layer:
Retrieval layer: recall and ranking of relevant evidence.
Answer layer: factual correctness, evidence support, citation accuracy, handling of unanswerable cases.
Tool layer: tool selection, parameter correctness, actual task completion rate, state after exceptions.
Engineering layer: P95 latency, failure rate, call rounds, cost.
Evaluation models can assist scoring, but critical business still needs human spot-checks and rule-based validation. Metric definitions, sample scope, and model versions must be archived to avoid incomparable tests.
20. When to Use Multi-Agent vs. Single Agent
If task path is fixed and tool count is small, a single Agent with deterministic workflow is easier to test and debug.
Consider multi-Agent when there are clear role separations, distinct tool permissions, independent contexts, or genuine parallelism. Decomposition incurs communication, coordination, latency, and evaluation overhead — do not split just because "multi-Agent sounds more advanced".
Design approach: build single-Agent baseline first, then compare success rate, latency, and cost on the same task batch to prove decomposition solves real problems.
Reverse Questions to Prepare
Never say "I have no questions." Suggested technical questions:
What business does the team currently own, and what will a new hire focus on?
How does backend development collaborate from requirements, testing, to deployment?
If the role involves AI, is the focus on knowledge QA, process automation, or intelligent enhancement of existing systems?
What are the concrete growth expectations for a new hire in the first few months?
Pick two or three you genuinely care about; also helps confirm role alignment.
Preparation Strategy for Next Interview
This round wasn't extremely deep but covered wide ground. HashMap, locks, thread pools, Redis, MySQL, Spring Boot are fundamentals; AI projects require explaining memory management, retrieval quality, node collaboration, and failure handling.
I will prepare a one-minute clear answer for each fundamental category, plus a concrete example. For projects, pre-draw call chains, clarifying what I built versus what I only know about.
Regarding coding tests: not encountering one this time was luck; no guarantee for next time, so keep practicing.
Offer secured, can finally breathe. Hope this retrospective helps others preparing for Java backend and AI application roles.
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.
SpringMeng
Focused on software development, sharing source code and tutorials for various systems.
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.
