Skip to content
Java Campus Recruitment Crash Course: From Core Concepts to Deployable Projects in 30, 60, or 90 Days

Java Campus Recruitment Crash Course: From Core Concepts to Deployable Projects in 30, 60, or 90 Days

A structured Java backend interview preparation guide covering core Java, MySQL, Spring ecosystem, Redis, message queues, microservices basics, deployment, and project practice with flexible 30-day, 8-week, and 12-week schedules for campus recruitment candidates.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

What Employers Actually Look For in Junior Java Candidates

Junior Java roles rarely require designing a flash-sale architecture from scratch. Instead, employers care about practical abilities:

Writing standard Spring Boot interfaces and understanding the Controller → Service → Mapper separation.

Writing business SQL, understanding indexes and transactions, and using EXPLAIN for slow queries.

Using Git, Maven, Linux; pulling a project locally, starting it, and reading logs when errors occur.

Having a genuinely self-written project, not just copying video tutorials.

Answering basic questions to the point and withstanding three layers of follow-up on every technology listed on the resume.

Learning order: First learn to use, then learn to explain, then learn to debug, finally study source code. For each knowledge point, leave three artifacts: a code commit, a resume bullet, and a 30-second verbal explanation.

Technology Priority Tiers

P0 Must Learn: Java basics, Collections, MySQL, Spring Boot, MyBatis, Redis, Git, Linux, Project, Algorithms, Interview Expression — Target: write code, explain core principles, complete project loop.

P1 Differentiator: Concurrency, JVM, MQ, Docker, Nginx, JWT, Validation, Logging, Unit Testing — Target: implement a small case, explain usage scenarios and pitfalls.

P2 Conceptual Awareness: Nacos, Gateway, OpenFeign, Sentinel, Seata, ES, XXL-JOB, Distributed Tracing — Target: know what problem it solves, ideally build a simple demo.

P3 Defer Deep Dive: K8s depth, ZGC tuning, distributed transaction source code, complex big data components, full Spring source code — Skip if time is tight; don't use to pad resume.

Skip Swing, AWT, Struts, EJB, JSP as main learning paths.

Engineering Environment: Run the Full Pipeline

JDK 8/11 remain common in existing projects; new projects can use Java 17 + Spring Boot 3. Toolchain essentials:

IDEA: run, debug, call hierarchy, navigate source.

Maven: dependency management, clean, compile, package, lifecycle, conflict resolution.

Git: add, commit, push, pull, branch, merge, rebase.

Postman/Apifox for API debugging; Swagger/OpenAPI/Knife4j for docs.

Navicat/DBeaver for DB operations and execution plans.

Linux, Docker, Nginx for deployment, logs, reverse proxy.

Don't just right-click run. Walk through the full cycle:

git clone <repo>
mvn clean package
java -jar target/app.jar
curl http://localhost:8080/user/1

On startup failure, verify JDK, Maven, Spring Boot versions; check application.yml for MySQL/Redis config, SQL import, port conflicts, dependency clashes.

Engineering highlight: Achieving docker-compose up -d to start MySQL, Redis, MQ, and the app in one command proves real project experience better than memorizing twenty commands.

Keep Git commits atomic; use prefixes like feat, fix. merge preserves branch history; rebase linearizes history but never rebase public commits already pushed and used by others.

Java Core: Connect Code to Principles

1. Basic Syntax & OOP

Must correctly use: 8 primitive types, autoboxing/unboxing, int vs Integer; Java is pass-by-value (reference value copy); array, overload, static/instance block, constructor execution order; encapsulation, inheritance, polymorphism, override vs overload, access modifiers, this / super; abstract class vs interface (abstract class can have constructor/state; interface fields are constants, Java 8+ default/static methods); generics, type erasure, wildcards; reflection, annotations basics; Lambda, Stream, Optional, LocalDate / LocalDateTime; String, StringBuilder, StringBuffer (single-threaded concatenation prefers StringBuilder, sync needs StringBuffer).

High-frequency questions — don't just memorize one-liners:

== vs equals() : == compares primitive values or reference addresses; Object default equals() compares addresses; String, Integer override to compare content.

Why override hashCode() when overriding equals() ? HashMap/HashSet use hash to locate bucket then compare equality. Equal objects with different hashes may land in different buckets, causing duplicates or misses.

Why is String immutable? Immutability enables security, hash caching, thread safety, constant pool reuse. Frequent modification creates many objects; internal array representation changes across JDK versions but the immutable design goal remains.

final , finally , finalize : final modifies class/method/variable (non-inheritable, non-overridable, reference/value non-reassignable). finally for resource release; not guaranteed on System.exit() or JVM crash; avoid return in finally as it may override prior return/exception. finalize() deprecated; use try-with-resources.

Exception hierarchy: distinguish Error, checked, unchecked. IO: File, byte/char streams, buffered streams, serialization/deserialization, NIO Buffer/Channel/Selector concepts. Serialization: watch serialVersionUID, field changes, sensitive data; don't use Java native serialization as cross-system protocol.

2. Singleton: Where Handwriting Reveals Gaps

Double-checked locking must understand volatile:

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

Second check avoids duplicate creation; volatile ensures visibility and prevents instruction reordering, stopping other threads from seeing a half-initialized object. Can also mention static inner class or enum singleton with their trade-offs.

3. Collections: Data Structure, Thread Safety, Resizing

ArrayList: Dynamic array, fast random access, resizes ~1.5x; most list business; contiguous memory friendly.

LinkedList: Doubly linked list, fast head/tail add/remove after node location; head/tail operations; node location still O(n).

HashSet: Backed by HashMap, uses equals/hashCode for deduplication; unordered deduplication.

TreeSet: Red-black tree, sorted by comparator; ordered set.

HashMap: Array + linked list + red-black tree, unordered, not thread-safe; high-frequency key-value lookup.

LinkedHashMap: Maintains insertion/access order; ordered Map, simple LRU.

TreeMap: Red-black tree, ordered; range queries, sorted keys.

ConcurrentHashMap: CAS + synchronized, finer-grained concurrency; concurrent cache, shared counters.

CopyOnWriteArrayList: Copy-on-write, read-heavy write-light; listener lists, etc.

Iterator fail-fast is concurrent modification detection, not thread-safety guarantee. Know Collections utilities. LRU: understand "HashMap for O(1) location, doubly linked list for usage order" and implement simple version with LinkedHashMap.

Why is HashMap Fast?

JDK 8 default capacity 16, load factor 0.75. put perturbs hash to involve high bits, then (n - 1) & hash for bucket index.

HashMap structure
HashMap structure

Treeification improves lookup from O(n) to O(log n); reverts to list when node count drops to ~6. Capacity must be power of two: enables bitwise & instead of modulo, and simplifies resize — nodes either stay or move to "old index + old capacity", avoiding full rehash.

Resize cleverness: Using one bit of the hash to decide node placement turns a full rehash into a two-way split — classic bitwise optimization to reduce resize cost.

HashMap not thread-safe; JDK 7 concurrent resize could cause dead loops; JDK 8 tail-insertion avoids that but concurrent put may still overwrite data, size inaccurate. ConcurrentHashMap JDK 8 drops Segment locking: empty bucket CAS write, non-empty bucket synchronized on head node; counters use baseCount + CounterCell[] to disperse contention. Key point: lock granularity shrank from Segment to single bucket, counting avoids central contention.

4. Concurrency: The Real Divider for Junior Roles

Master three thread creation ways: Thread, Runnable, Callable; understand six thread states.

Thread states
Thread states

JMM focus: visibility, atomicity, ordering: volatile guarantees visibility, forbids specific reordering, does not guarantee atomicity . i++ still needs AtomicInteger or locks.

CAS is lock-free foundation; watch ABA, spin overhead.

AQS underpins ReentrantLock, Semaphore; at campus stage understand "state + wait queue". CompletableFuture for async orchestration; ThreadLocal for thread-level context isolation.

Comparison of synchronized vs ReentrantLock:

Implementation: JVM Monitor vs API layer, AQS-based.

Lock release: Automatic vs must unlock() in finally.

Interruptible/Timeout: No vs Yes: lockInterruptibly(), tryLock().

Fairness: Non-fair vs Configurable fair/non-fair.

Condition queues: wait/notify single vs Multiple Condition objects. synchronized also covers lock object, scope, biased/lightweight/heavyweight lock progression concepts — no need to memorize every JVM version detail. ThreadLocal: each thread has independent ThreadLocalMap, key is weak reference to ThreadLocal, value is data. In thread pools threads are reused; failure to clean causes stale reads and memory leaks:

try {
    UserContext.set(currentUser);
    // business logic
} finally {
    UserContext.remove();
}

Thread Pool Seven Parameters & Execution Flow

Parameters: corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler.

Thread pool execution flow
Thread pool execution flow

Four rejection policies: AbortPolicy (throw exception, default), CallerRunsPolicy (caller executes, backpressure), DiscardPolicy (silent drop), DiscardOldestPolicy (drop oldest, retry).

CPU-intensive: start near "CPU cores + 1"; IO-intensive: start near "CPU cores × 2" or higher, but real config must consider IO wait, downstream capacity, queue backlog, monitoring — formulas are not gospel.

Pitfall alert: Avoid Executors for production pools. FixedThreadPool default unbounded queue, CachedThreadPool unbounded thread creation — both risk OOM. Production: manually specify bounded queue, thread name, rejection policy, fallback logic .

Practice: multi-thread print ABC, fixed pool + producer-consumer, multi-thread inventory deduction. Must not only run but explain queue/rejection strategy choices.

5. JVM: No Source Code Memorization, But Must Walk Troubleshooting Paths

Runtime data areas: thread-private (PC register, VM stack, native method stack); thread-shared (heap, method area — Metaspace in HotSpot). Heap: Eden, Survivor, Old; objects may allocate via TLAB in Eden, large objects directly to old, JIT may do stack allocation.

GC Roots: VM stack references, static variables, constants, native method stack references. Reachability analysis determines liveness.

Mark-Sweep: Simple, may produce fragmentation; CMS old gen, etc.

Copying: Simple allocation, no fragmentation, wastes space; Young gen.

Mark-Compact: Moves objects after sweep, reduces fragmentation; Old gen.

Generational Collection: Different strategies per object lifetime; Most mainstream collectors.

Key collectors: Serial/ParNew (young gen, copying); CMS (concurrent low pause, fragmentation, retired); G1 (default from JDK 9, Region-based, pause target, Mixed GC); ZGC/Shenandoah (low pause, bonus knowledge).

Class loading:

Loading → Verification → Preparation (zero values) → Resolution → Initialization (static initializers)

.

Parent delegation: "ask parent first, load self if parent cannot", ensures core library safety and class consistency. JDBC SPI (context class loader), Tomcat (app isolation), OSGi extend/break this model.

Common JVM params:

-Xms4g -Xmx4g
-Xmn2g
-XX:+UseG1GC
-XX:MetaspaceSize=256m
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/tmp/dump.hprof
-Xms

= -Xmx reduces heap resize jitter; -Xmn is traditional generational config, don't mechanically apply with G1.

CPU 100% Troubleshooting:

top
top -Hp <PID>
printf '%x
' <TID>
jstack <PID>
jstat -gcutil <PID> 1000

Convert thread ID to hex, find matching nid in jstack. Common causes: infinite loops, catastrophic regex backtracking, lock contention, frequent GC. Arthas thread -n also locates high-CPU threads.

OOM Troubleshooting:

Configure OOM auto-dump on startup; use jmap -dump manually if needed.

Use MAT, VisualVM, JProfiler to view Dominator Tree, find large objects and reference chains.

Check static Map unbounded growth, large collections not released, ThreadLocal leaks, full-table queries, large object serialization.

Off-heap: check NIO DirectByteBuffer; Metaspace: check CGLIB dynamic class generation. jps, jstack, jmap, jstat, Arthas — walk at least one full troubleshooting path.

MySQL: Complete Optimization Loop Differentiates Candidates

1. Write SQL Fluently Before Optimizing

Master DDL, DML, CRUD, PK/column types, three normal forms. Business query practice: INNER/LEFT/RIGHT JOIN, GROUP BY, aggregates, subqueries, pagination, window functions basics; common date/string/aggregate functions; optimistic locking, logical deletion, time/status order queries; daily at least one SQL — handwrite grouped TOP1, join statistics.

SELECT o.order_no, u.name, p.product_name
FROM orders o
JOIN users u ON o.user_id = u.id
JOIN products p ON o.product_id = p.id
WHERE o.create_time > '2024-01-01'
ORDER BY o.amount DESC
LIMIT 10;

Passing standard: independently design project tables, write 20 business SQLs, keep at least 3 slow SQL optimization records.

2. Why InnoDB Favors B+ Tree

Hash: Fast equality, poor range/sort.

Red-Black Tree: Binary, tall tree with large data, more disk I/O.

B-Tree: Non-leaf nodes store data, fewer keys per page.

B+ Tree: Non-leaf nodes store keys only, shorter tree; leaf nodes ordered & linked, great for range scans.

InnoDB primary index is clustered (leaf stores full row); secondary index leaf stores PK value — querying non-indexed columns requires lookup back to primary index (回表) . If query columns are all in index, forms covering index (覆盖索引) , avoids lookup. Hence avoid habitual SELECT *; select only needed columns.

Composite index: understand leftmost prefix, index condition pushdown, ordering utilization. Differentiate primary, unique, normal, composite indexes in table design context.

3. Index Failure: Not a Mnemonic, But Ability to Fix SQL On-Spot

Common risk scenarios:

Composite index violates leftmost prefix.

Function/calculation on indexed column, e.g., WHERE YEAR(create_time) = 2024 → rewrite as time range.

Implicit type conversion.

Leading wildcard LIKE '%xx'. OR connects column without suitable index. NOT IN, some IS NULL may affect index usage depending on data distribution — don't absolutize as guaranteed failure .

Optimizer estimates high lookup cost, prefers full scan (low cardinality, large result set).

Reading EXPLAIN focus: type (access type, ALL = full scan), key (actual index used), rows (estimated scanned rows), Extra (watch Using filesort, Using temporary, identify covering index, index condition pushdown).

Don't treat "type must reach X level" as iron law. Index effectiveness depends on query selectivity, scanned rows, lookup cost, actual execution time.

4. Transaction, MVCC, Locks, Logs — Tell Them as a Story

ACID: Atomicity, Consistency, Isolation, Durability — isolation is the deep-dive favorite.

Read Uncommitted: Dirty reads possible; can read other transactions' uncommitted data.

Read Committed (RC): Avoids dirty reads, non-repeatable reads possible; each snapshot read sees latest committed.

Repeatable Read (RR): Avoids non-repeatable reads, phantom reads still discussed; InnoDB default.

Serializable: Lowest concurrency; stronger locking for isolation.

MVCC relies on hidden transaction fields, undo log version chain, ReadView visibility checks. Ordinary snapshot reads usually lock-free; SELECT ... FOR UPDATE current reads require locks.

"Does RR solve phantom reads?" — don't give a one-liner:

For snapshot reads, RR's consistent view avoids new rows appearing in repeated queries within same transaction.

For current reads, InnoDB uses record locks + gap locks = Next-Key Lock to prevent inserts in range.

So separate MVCC and locking mechanisms; don't blanket say "MVCC solves all phantom reads".

Row locks, table locks, gap locks, deadlocks — understand all. redo log for crash recovery, undo log for rollback & MVCC, binlog for archiving/replication.

Deadlock investigation: SHOW ENGINE INNODB STATUS; Check LATEST DETECTED DEADLOCK, analyze lock acquisition order. Common fixes: unify lock order, shorten transactions, reduce lock scope, set reasonable innodb_lock_wait_timeout — not infinite increase.

5. Slow SQL Optimization Full Loop

Slow SQL optimization flow
Slow SQL optimization flow

Typical case: order list query WHERE user_id = ? AND status = ? ORDER BY create_time DESC. Originally only single-column index on user_id; as data grew, latency rose from ~200ms to 1.2s, EXPLAIN showed type=ALL and Using filesort. Created composite index (user_id, status, create_time); plan improved to ref, sort no longer filesort, latency dropped to ~80ms.

Value is not the numbers but the sequence: Detect → Explain → Design Index → Re-test Verify .

Other techniques: enable slow query log ( slow_query_log=ON, set long_query_time); deep pagination LIMIT 1000000, 10 → cursor pagination WHERE id > ? LIMIT 10; large table exact COUNT(*) costly → consider cache, stats table, approximation; shorten large transactions, handle lock waits; when indexing insufficient, then consider cache, read-write split, sharding; "shard at 20M rows" is only heuristic — real decision depends on row width, indexes, query patterns, hardware.

Spring Ecosystem & Web: From Annotations to Request Lifecycle Explanation

1. JavaWeb Fundamentals Not to Skip

HTTP methods, headers, status codes, GET/POST semantics; Tomcat architecture, Servlet init → service → destroy lifecycle; Filter, Listener; Cookie/Session/Token differences, Redis distributed session; RESTful, JSON, RBAC, idempotency, rate limiting; CORS origins, gateway unified CORS, proxy same-origin solutions.

Filter closer to Servlet container; Interceptor closer to Spring MVC Handler invocation; where to put auth/logging/permission depends on whether Spring context and specific Handler are needed.

JWT = Header.Payload.Signature; stateless, good for distributed, but Payload ≠ encryption — don't put sensitive data directly.

JWT logout can't just be "frontend deletes token". Options: Redis blacklist; user token version increment on password change; short-lived Access Token + Refresh Token renewal. Illustrates trade-off between statelessness and controllable invalidation .

2. Spring IoC, AOP, Bean Lifecycle

IoC = container manages object creation & dependencies; DI = container injects dependencies. Benefits: decoupling, easy implementation swap, testability — not just "fewer new calls".

AOP extracts cross-cutting logic (logging, transactions, permissions). JDK dynamic proxy targets interfaces; CGLIB generates subclass proxies; Spring Boot 2.x+ defaults to CGLIB.

Bean lifecycle — don't memorize 10+ steps, but clarify key phases:

Bean lifecycle
Bean lifecycle

Scopes: singleton, prototype, request, session (web).

Why Three-Level Cache Breaks Circular Dependencies?

singletonObjects

: fully initialized singleton beans. earlySingletonObjects: early exposed references. singletonFactories: ObjectFactory for on-demand early object/proxy creation.

A instantiates, exposes factory, then creates B; B needs A, gets early reference, breaking setter/field injection cycle. Third-level factory also handles proxy creation when needed, avoiding final object vs proxy mismatch.

Constructor circular dependencies usually cannot be resolved by three-level cache because object not yet instantiated but needs the other dependency. Fix via redesign, @Lazy — don't blindly switch all injections to field injection.

3. Spring Transactions: Failure Scenarios Worth More Than Definitions

@Transactional

— understand propagation, isolation, rollback rules. Common failure scenarios:

Method not public — proxy can't apply.

Self-invocation within same class — this bypasses proxy.

Exception caught and swallowed — transaction unaware of failure.

Checked exception thrown without rollbackFor = Exception.class.

Bean not managed by Spring.

DB engine doesn't support transactions (e.g., MyISAM).

Propagation misuse — confusing REQUIRED vs REQUIRES_NEW boundaries.

Execution in new thread/async — original transaction context not naturally propagated.

Self-invocation fix: extract to another bean, or obtain current proxy if proxy mechanism clear; don't overcomplicate just for transaction.

Practical reminder: Long transactions hold DB connections and row locks. Move RPC, file IO, heavy computation out of transaction; keep only DB operations that must be atomic.

4. Spring MVC: Separate Traditional Views from JSON APIs

Spring MVC flow
Spring MVC flow

Parameter binding, @Valid validation, global exception, unified response are project standards: @RestControllerAdvice unified exception handling.

Response body standardized as code/msg/data.

Even intentional empty params should return structured error, not stack trace.

Business logic not in Controller; transactions not on Controller.

5. Spring Boot: Auto-Configuration Isn't Magic

@SpringBootApplication

combines:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
Spring Boot auto-configuration
Spring Boot auto-configuration

Old versions used META-INF/spring.factories; new versions use AutoConfiguration.imports. Custom starter core: auto-config class + conditional annotations + registration file + sensible default dependencies.

Config files: multi-environment isolation. Rough priority: "command line args > Java system props > environment variables > external config > internal config"; profile-specific overrides common; .properties higher priority than YAML for same property at same location. Details vary by Spring Boot version — refer to current docs.

Spring Boot must quickly integrate MyBatis, Redis, Druid; understand Starter, embedded Tomcat, "convention over configuration".

6. MyBatis & MyBatis-Plus

Essential difference between #{} and ${} : #{} uses PreparedStatement placeholder, prevents SQL injection. ${} is string concatenation, injection risk.

Dynamic table names, ORDER BY columns can't be bound as parameters — only then consider ${} with strict whitelist validation.

Mapper interface has no implementation but executes via JDK dynamic proxy generating MapperProxy, which finds MappedStatement by interface/method, delegates to MyBatis. Know core components: SqlSession, Executor, StatementHandler, ResultSetHandler.

Caching: L1 cache is SqlSession -level, default on; different sessions, updates, commit/rollback, cache clear affect reuse. L2 cache is Mapper/namespace-level, explicit enable, multi-table/distributed consistency issues — production often prefers Redis.

Dynamic SQL: if, where, set, foreach tags. Lazy loading via fetchType="lazy" in association mapping.

MyBatis-Plus: master LambdaQueryWrapper, pagination plugin, logical deletion. Suggested layering:

controller / service / mapper / entity / dto / vo
config / common / exception

Redis: What Differentiates Isn't Five Types, But Cache Governance

1. Data Structures by Business Scenario

String: Object JSON, counters, verification codes, distributed locks.

Hash: User objects, shopping carts — partial updates.

List: Simple queues, latest lists.

Set: Deduplication, mutual friends, lottery.

ZSet: Leaderboards, score-based delayed tasks.

BitMap: Sign-in, boolean states, deduplication stats.

HyperLogLog: Massive UV estimation, memory-efficient with error.

GEO: Location-based queries.

Hash vs String memory savings depends on field count and encoding — don't absolutize. ZSet delayed queue needs compensation and idempotency, not just polling.

Redis speed: in-memory ops, efficient structures, I/O multiplexing, low-contention command execution. Redis 6+ introduces multi-threaded network I/O, but core command execution remains single-threaded in essence.

2. Cache-Aside: Read, Write, Consistency Together

Cache-Aside pattern
Cache-Aside pattern

Update: update DB first, then delete cache , not delete cache then update DB. Delayed double-delete reduces some concurrent dirty-read probability but can't guarantee absolute consistency; stronger needs can combine Canal binlog listening for async cache repair, accepting some delay.

3. Penetration, Breakdown, Avalanche — One-Sentence Distinction

Penetration: Query non-existent data, cache never hits; DB has no data. Solutions: param validation, short-TTL empty-value cache, Bloom filter.

Breakdown: Single hot key expires, massive concurrent rebuild; DB has data. Solutions: mutex rebuild, logical expiration, async refresh.

Avalanche: Mass keys expire simultaneously, or Redis crashes; DB usually has data. Solutions: TTL + random, multi-level cache, rate limiting/degradation, HA.

Bloom filter: bit array + multiple hash functions. "Not exist" is certain; "exist" may be false positive. Standard Bloom filter doesn't support deletion; Counting Bloom Filter supports counting deletion at higher cost.

Practical product detail solution: Cache-Aside + 2-min empty cache + Redisson mutex rebuild + TTL randomization . Solutions must map to specific problems — don't add locks to every key.

4. Distributed Lock: Direct DEL Is the Biggest Pitfall

Lock acquisition must atomically combine "set value, NX, expiry"; value = unique token (UUID):

String token = UUID.randomUUID().toString();
String key = "lock:order:1001";

String result = redis.set(
    key,
    token,
    SetParams.setParams().nx().ex(10)
);

if ("OK".equals(result)) {
    try {
        // business logic
    } finally {
        String script =
            "if redis.call('get', KEYS[1]) == ARGV[1] then " +
            "return redis.call('del', KEYS[1]) " +
            "else return 0 end";
        redis.eval(
            script,
            Collections.singletonList(key),
            Collections.singletonList(token)
        );
    }
}

Lua unlock ensures "compare value and delete" atomic. Plain redis.del(key) may delete another's lock after yours expires.

Further considerations:

Business not done before lock expiry: Redisson watchdog auto-renewal (default lease ~30s, renew at ~1/3 interval).

Reentrancy: Redisson uses Hash to track reentry count.

Master-slave switch losing lock: RedLock is debated; strong consistency needs architecture re-evaluation.

Lock code must use try-finally, but finally must still verify identity.

Redis/Redisson: High performance, easy integration; master-slave switch, lease/renewal handling; most internet mutex scenarios.

ZooKeeper ephemeral sequential nodes: Stronger consistency & lock semantics; higher performance & ops cost; consistency-critical scenarios.

DB unique index: Simple, no new components; limited concurrency performance; low concurrency, fallback deduplication.

5. Persistence, Expiration, Cluster

RDB: snapshots, fast recovery, may lose data since last snapshot.

AOF: append commands, higher durability, larger files & slower recovery.

Hybrid: AOF rewrite combines RDB content + subsequent incremental commands — common in production.

Expiration: lazy deletion + periodic deletion.

Eviction: know noeviction, allkeys-lru, volatile-lru, random — cache and persistent data shouldn't share eviction logic.

HA: master-slave for replication/read scaling; Sentinel for auto failover; Cluster shards via 16384 slots.

MQ, Microservices, Deployment: Know Boundaries Better Than Stacking Components

1. Message Queue: Beyond Async/Peak-Shaving/Decoupling, Answer the Cost

Pick one (RabbitMQ, RocketMQ, Kafka) to go deep — don't list "familiar with all" on resume.

RabbitMQ: producer, consumer, Queue, Exchange, four exchange types:

Direct: Exact Routing Key match; explicit business routing.

Fanout: Broadcast to bound queues; notifications, multi-consumer replicas.

Topic: Wildcard pattern match; multi-dimensional event classification.

Headers: Message header attribute match; special attribute routing.

General concepts: Topic, Queue, Consumer Group, Offset, message ordering, backlog, dead-letter queue, transactional messages.

Message loss prevention across three ends:

Producer: confirm/ack, retry, critical messages persisted locally.

Broker: message persistence, configure sync flush, replicas, master-slave per component capability.

Consumer: manual ack/offset commit after successful processing; failures go to retry/DLQ — never swallow exceptions.

Don't promise "absolutely no duplicates". Network retries and failure recovery make duplicates inevitable; reliable goal is consumer idempotency:

Unique message ID + Redis deduplication.

DB unique index or deduplication table.

State machine validation to prevent repeated state transitions.

Ordering: single partition, single consumer, or business-key routing for local ordering — sacrifices parallelism. Backlog: temporarily scale consumers, batch consume, investigate slow SQL/downstream bottlenecks, degrade — don't just infinitely add machines.

Practice: async notification after order, send SMS, add points, operation log enqueue.

2. Microservices: Draw Clear Call Chains Before Advanced Features

Spring Cloud Alibaba: Common microservice component suite.

Nacos: Service registration/discovery & config management.

Gateway: Unified routing, auth, rate limiting entry.

OpenFeign: Declarative HTTP service calls.

Sentinel: Rate limiting, circuit breaking, degradation.

Seata: Distributed transactions — know AT, aware of TCC/Saga.

SkyWalking/Zipkin: Distributed tracing.

ES: Search scenarios, project bonus.

XXL-JOB: Distributed scheduling, task deduplication via distributed lock.

Microservice architecture
Microservice architecture

Cascade failure governance needs timeout, limited retries, circuit breaker, degradation, rate limiting together. Unlimited retries amplify traffic and may cause duplicate writes — must limit retries and ensure idempotency.

Distributed ID: understand Snowflake "timestamp + machine ID + sequence"; Nacos CP/AP modes via registration vs config scenarios; distributed transactions: don't just memorize Seata AT — know it solves cross-service data consistency and adds complexity.

3. Linux, Docker, Nginx: Project Isn't Complete Until It's Live

Common commands for troubleshooting:

tail -f app.log
grep "traceId" app.log
ps -ef
top
jps
netstat -anp
ss -lntp
curl http://localhost:8080/health
chmod +x app.sh
awk '{print $1}' app.log

On production error: tail -f real-time logs, grep for traceId/exception class/key params, correlate with request time, slow SQL, Redis, downstream APIs, machine resources.

Docker commands:

docker ps
docker logs <container>
docker exec -it <container> bash
docker build -t my-app .
docker-compose up -d

Nginx: understand reverse proxy and basic config. Project must achieve:

Git for code & branch management.

Maven packaging & dependency conflict resolution.

Docker starting MySQL, Redis, backend service.

Nginx as unified entry.

Local or cloud deployment, config per environment.

JUnit basic unit tests, logs with traceId.

Interface 500 Troubleshooting Order: Reproduce & record params/traceId; check gateway & app exception stacks; then DB, Redis, third-party APIs, resource usage. Rollback first if impact widening; then patch, add logs, test, retrospective.

Interface Slowness Troubleshooting Order: Monitoring: overall or single API → tracing per hop → check slow SQL, cache hit rate, GC, thread pool, Druid pool, downstream RPC, lock contention. jstack for BLOCKED, jstat -gcutil for frequent GC.

Project Practice: One Defensible Project Beats Three Half-Baked Ones

1. Topic Selection

Enterprise User Management: SSM + JSP + MySQL + Maven; user CRUD, pagination, login interceptor, permissions — SSM integration, MVC layering, good for traditional practice.

Blog/Community/Short Link/Campus Appointment: Spring Boot 3 + MyBatis-Plus + MySQL + Redis + JWT + Docker + Nginx — auth, content publishing, categories/tags, comments/likes/favorites, caching, slow SQL optimization.

RBAC Permission Backend: Spring Boot + Spring Security/Sa-Token + JWT + Vue — role permissions, token auth, operation logs.

Flash Sale/Coupon/Order: Spring Boot 3 + Redis + Redisson + one MQ + MySQL + JMeter — oversell prevention, idempotency, async ordering, rate limiting, cache consistency.

Online Collaborative Document: Spring Boot + WebSocket + MySQL — real-time editing, version control.

User/Order Microservice Demo: Nacos + OpenFeign + Gateway — registration/discovery, gateway entry, service call & protection.

Teaching projects (e.g., Regi Takeout, Cangqiong Takeout) can be starting points but must add a real optimization. Pure CRUD malls, library systems, copy-paste video projects — hard to differentiate.

Baseline project must close the loop:

Register/login, token refresh & logout.

Role permissions, CRUD, pagination, conditional query.

File upload, state transition, operation logs.

Param validation, unified response, global exception.

API docs, basic unit tests.

Redis hot cache, cache penetration prevention.

Unique index for duplicate like/claim prevention. EXPLAIN optimization records, Docker Compose deployment.

2. Six Highlights — Pick Three or Four to Deepen

Auth: JWT + Redis blacklist or token version, complete logout & renewal.

Idempotency: Unique request ID, anti-replay token, Redis SET NX, DB unique index, state machine, optimistic lock version.

Cache Design: Cache-Aside, empty cache, mutex rebuild, random TTL, consistency repair.

Async Decoupling: MQ peak-shaving + confirm + persistence + manual ack + idempotent consumption + DLQ.

Scheduled Tasks: XXL-JOB distributed scheduling, distributed lock to prevent duplicate execution.

High-Concurrency Chain: Redis Lua atomic pre-deduct inventory + MQ async ordering + DB fallback.

Anti-duplicate submission in three layers:

Frontend: button disable, anti-replay token.

Gateway/interceptor: Redis on userId + URI + param hash with short TTL.

DB: unique index & state machine as final guard.

3. How to Articulate Flash Sale Design Trade-offs

Flash sale architecture
Flash sale architecture

DB optimistic lock via version or stock > 0 condition update. Redis pre-deduction reduces DB pressure; MQ converts instantaneous sync traffic to consumable tasks; unique index provides final deduplication.

Don't write "used distributed lock so absolutely no oversell". Lock is only part; DB constraints, idempotency, failure compensation equally important.

Order auto-close on timeout unpaid — options:

RocketMQ delayed messages.

RabbitMQ dead-letter queue.

Redis ZSet polling by expiry time.

Scheduled task scanning table — simple but higher latency & scan pressure.

Regardless of method, before closing must re-query order status to ensure idempotency, avoid closing already-paid orders.

4. Project Metrics: Don't Be a "Resume Poet"

Project must answer:

What business problem solved?

Which chain were you specifically responsible for?

Why this technology, what alternatives compared?

Biggest challenge and pitfall?

How quantified results?

What would you change if redone?

Qualified answer structure:

Background & Goal → Tech Selection Reasoning → My Concrete Implementation → Problems Encountered → Solutions & Trade-offs → Quantified Results → Future Optimizations.

Example:

Product detail peak traffic hit MySQL directly, connection pool near exhaustion, P99 spiked. I introduced Cache-Aside: update DB then delete cache; empty cache for penetration; Redisson mutex for hot key rebuild. Verified via JMeter load test and cache metrics — observed DB query volume and latency changes.

If resume claims "cache hit rate 92%", must explain measurement:

Micrometer + Prometheus collecting cache.gets, cache.hits.

JMeter load testing read-heavy write-light scenario in test env for fixed duration.

Grafana observing stable window.

How hit rate, QPS, P99, error rate calculated.

Every number on resume must be reproducible. No load test? Write "local load test", don't fake production data. Can't explain source? Delete it.

Algorithms, Networking, OS: Don't Crash at Final Hand-Coding Round

1. Algorithm Scope — Don't Spread Too Wide

Must-know data structures: array, string, linked list, stack, queue, hash table, binary tree, heap.

Must-practice techniques: sorting, binary search, two pointers, sliding window, recursion, BFS/DFS, backtracking, DP basics.

High-frequency topics:

Two Sum, Three Sum.

Reverse linked list, merge two sorted lists, cycle detection.

Valid parentheses, Min Stack.

Binary tree traversals, max depth, invert tree, LCA.

Binary search with left/right boundaries.

TopK, LRU Cache.

Climbing stairs, max subarray sum.

Longest palindromic substring, LIS.

Permutations, subsets.

Time-constrained: finish ~50 easy/medium from LeetCode Hot 100; full cycle: 80-100 with second pass on mistakes. Daily 1-2 problems, plus 5 handwritten SQLs and a few concurrency mini-problems.

Interview: state brute force first, then optimize to hash/two pointers/binary search/DP, finally give time/space complexity. Pre-check empty array, single element, duplicates, overflow; post-check run edge cases.

2. Computer Networking Top Five Questions

TCP Three-Way Handshake: SYN → SYN+ACK → ACK; not two-way to avoid stale connection requests wasting resources.

TCP Four-Way Handshake: Bidirectional FIN/ACK; TIME_WAIT waits 2MSL for final ACK retransmission and old segment expiry.

TCP vs UDP: TCP connection-oriented, reliable, ordered; UDP connectionless, low overhead, no reliability guarantee.

HTTP 1.1/2/3: 1.1 keep-alive; 2 binary framing, multiplexing, header compression; 3 QUIC-based, improves transport-layer head-of-line blocking.

HTTP vs HTTPS: HTTPS verifies identity via certificate, negotiates session key in handshake, then mainly symmetric encryption.

"Enter URL to page display" chains DNS, TCP, TLS, HTTP, server processing, browser rendering.

3. OS: Remember Three Main Threads

Process = resource allocation unit; Thread = CPU scheduling unit; Coroutine = lighter user-space execution unit.

IPC: pipes, message queues, shared memory, sockets.

Deadlock four conditions: mutual exclusion, hold-and-wait, no preemption, circular wait; prevention = break at least one.

Scheduling Time: Full Cycle Builds Foundation, Short Cycle Cuts Breadth Not Projects

1. 12-Week Complete Version

Week 1: Java basics, Collections, IDEA, Maven — Console student grade system — practice collections, exceptions, files, Stream.

Week 2: Collections source, Stream, IO, common interview topics — Simple HashMap, word frequency, LRU demo.

Week 3: Concurrency, thread pools, locks — Multi-thread inventory deduction, print ABC alternating, producer-consumer.

Week 4: JVM, GC, troubleshooting tools — CPU 100% & OOM troubleshooting notes, memory leak observation case.

Week 5: MySQL, indexes, transactions, locks, EXPLAIN — 1M-row test table, slow SQL optimization case.

Week 6: Redis, cache issues, distributed locks — Product cache, penetration prevention, Redisson lock demo.

Week 7: Spring, Spring Boot, MyBatis-Plus — Full CRUD, param validation, unified response, global exception.

Week 8: Auth, API standards, logging, Docker — Deployable project version.

Week 9: MQ, async, idempotency — Async ordering or notification demo.

Week 10: Microservices concepts or second project — User/Order two services; skip if time tight.

Week 11: Project polish, load testing, highlight refinement — README, load test report, before/after execution plans.

Week 12: Resume, algorithms, mock interviews — One-page resume, Q&A handbook, 3 recorded mock interviews.

2. Only 8 Weeks

Weeks 1-2: Java basics, collections, concurrency, JVM.

Week 3: MySQL indexes, transactions, locks, SQL optimization.

Weeks 4-5: JavaWeb, Spring, Spring MVC, Spring Boot, MyBatis.

Week 6: Redis, Maven, Git, RabbitMQ.

Week 7: One complete project — start with user management practice, then polish blog/order project.

Week 8: Algorithms, networking, OS, high-frequency questions, resume, applications.

3. Only 30 Days

Days 1-3: Env, Maven, Git, Spring Boot — Runnable demo, API curl works.

Days 4-8: Java Collections, String, Exceptions, Stream — 10 high-frequency topics verbalized.

Days 9-14: MySQL, indexes, transactions, SQL — Table design, 20 SQLs, slow query case.

Days 15-23: Spring Boot + MyBatis-Plus project — Login, CRUD, pagination, exception, validation.

Days 24-26: Redis, JWT, Docker, Linux — Cache, auth, deployment.

Days 27-28: Thread pools, JVM, HTTP, troubleshooting — Troubleshooting handbook.

Days 29-30: Algorithms, resume, mock interviews — Finalized resume, 3 mock interviews.

21-day emergency: compress further — days 1-3 Java, 4-5 MySQL/MyBatis, 6-8 Spring, 9-10 Redis/MQ, 11-14 project, 15-16 microservice concepts, 17-18 algorithms, 19-20 mock interviews, day 21 apply & retrospective.

Only 6 weeks: cut microservices and second project, keep Spring Boot + MySQL + Redis monolith project . Day 7: API runs; Day 30: MySQL & Redis integrated; Day 60: deployment & resume finalized — these three milestones beat "how many video episodes watched".

Resume, Applications, Interviews: Articulate What You Know

1. Resume Project Description Formula

Recommended: Business Action + Technical Mechanism + Constraints + Verifiable Result.

Counterexample: "Used Redis to cache product data, improved system performance."

Better: "For hot product details, applied Cache-Aside, short-TTL empty cache, Redisson mutex rebuild; validated via JMeter & Micrometer metrics showing cache hit rate, DB query volume, P99 improvements."

Template:

Campus appointment backend with Spring Boot + MyBatis-Plus + MySQL + Redis
- Completed login auth, pagination CRUD, state transition, param validation, unified exception
- Optimized list query via composite index & EXPLAIN, reduced useless scans & extra sorts
- Handled concurrent state changes & duplicate appointments with optimistic lock & unique index
- Cached hot data with Redis, reduced penetration risk via empty-value cache
- Provided API docs, basic unit tests, Docker Compose deployment config

If flash sale done, add Redis pre-deduction, Redisson, MQ async ordering, unique order ID, JMeter load test. Don't write "proficient", don't stack undone tech, don't package tutorial projects as production.

2. Self-Intro & Project Intro

30-second self-intro highlighting facts:

Hello, I'm XX, targeting Java backend. I independently built a Spring Boot project with login auth, pagination CRUD, Redis cache, unified exception and slow SQL optimization, deployed via Docker. I can focus on cache design and concurrent state control.

Prepare 1-min project intro and 3-min deep-dive. Talk less about "we did", more about "I decided X because Y".

Unknown question? Don't bluff:

I haven't production-practiced this point, so I won't claim familiarity; but I understand it mainly solves... If I had to troubleshoot, I'd start by... I'll fill this gap after the interview.

3. Behavioral, Reverse Questions, Salary

Your weakness? Real but non-fatal, with ongoing improvement action.

Why our company? Combine industry, tech stack, role business, team — not just "big platform".

How solve technical challenges? Reproduce & read docs → search & locate → read source if needed → ask colleagues → retrospective.

View on overtime? Support during crunch, but value efficiency & long-term sustainability.

Reverse questions: "Which business line does this role own?", "Team's current stack & roadmap?", "Expectations for campus hires in first 3 months?", "Code review & collaboration process?"

Application priority: internal referral → campus portal → BOSS Zhipin, NowCoder, InternSG. Apply ~10 practice companies first, use real interviews to expose gaps, patch same day, then target dream companies — don't waste first interview on top choice.

Salary: confirm base, performance, year-end bonus, allowances, probation length/discount, social insurance base. Phone interviews: not in canteen or street; don't sign offer without clarifying structure.

Final Acceptance Criteria: Meet These Before Mass Applications

Project runnable, Git has continuous commit history.

Can cold-start clone → package → java -jar → curl.

Can explain 10 high-frequency topics with project examples.

Can write common business SQL, interpret EXPLAIN, describe one slow SQL optimization.

Can troubleshoot 500 errors, slow SQL, cache inconsistency, CPU 100%, common OOMs.

Algorithm easy problems stable, medium can articulate approach, handwritten code checks boundaries.

Every resume tech point withstands three-layer follow-up; every number explainable.

Completed ≥3 mock interviews, recorded, playback, removed stalls and fluff.

Daily check: code written, problems reviewed, project highlights added, can explain off-script.

Resources — don't hoard: Java concurrency — Java Concurrency in Practice + official Javadoc; JVM — core chapters of Understanding the Java Virtual Machine ; MySQL — How MySQL Works + EXPLAIN hands-on; Redis — Redis Design and Implementation + official docs; Spring source — only Bean lifecycle, circular dependency, auto-configuration; Algorithms — LeetCode Hot 100 + handwritten LRU.

Real crash-course competition isn't "how much learned", but whether every resume point can land, be explained, and survive grilling. Project runs, questions answered, bugs debugged — you're no longer just a route-collector.

If starting this roadmap, do first thing today: get a Spring Boot API running and commit to Git. Found this checklist useful? Like, "watch", save as punch-card.

How far from applying? What's the biggest blocker — HashMap, MySQL, project, or deployment debugging? Comment "remaining time + current blocker" and I'll judge next priority by campus interview standards.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaMicroservicesBackend DevelopmentRedisSpring BootMySQLInterview PreparationCampus Recruitment
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.