Essential Java, Spring, MySQL, Linux & Redis Interview Questions for Backend Developers
A comprehensive collection of over 70 interview questions covering Java concurrency, Spring framework, MySQL optimization, JVM internals, Linux command-line tricks, Redis usage, and system monitoring, designed to help backend engineers prepare for technical interviews across major Alibaba subsidiaries.
Java Concurrency
When read‑heavy workloads dominate writes, use a ReadWriteLock (e.g., ReentrantReadWriteLock) so multiple readers can proceed concurrently while writers acquire an exclusive lock.
Java AbstractQueuedSynchronizer (AQS) is a framework for building synchronizers (locks, semaphores, barriers). It manages a FIFO wait‑queue and provides acquire / release methods that subclasses implement.
Beyond synchronized, thread safety can be achieved with java.util.concurrent utilities: Lock implementations, Atomic* classes, ConcurrentHashMap, ThreadLocal, and immutable objects.
The volatile keyword guarantees visibility of writes to other threads and prevents reordering, but it does **not** provide atomicity for compound actions.
If a thread pool’s workers are all busy, a new task is placed in the pool’s work queue. If the queue is bounded and full, the RejectedExecutionHandler is invoked (default throws RejectedExecutionException).
Typical Tomcat tuning includes adjusting maxThreads, minSpareThreads, acceptCount, connection timeout, and enabling APR/native connector for better I/O performance. synchronized locks the monitor associated with an object. In bytecode it appears as monitorenter and monitorexit. At runtime the monitor is stored in the object header. wait, notify, and notifyAll must be called from inside a synchronized block (or method) because they operate on the object's monitor.
Best practice is to create a single ExecutorService per application (or per logical component) and share it; this reduces thread‑creation overhead and simplifies shutdown.
Spring Framework
Spring AOP provides declarative cross‑cutting concerns (logging, security, transactions). It is applied via @Aspect classes and @Around / @Before / @After advices, usually enabled with @EnableAspectJAutoProxy.
When an interface has multiple implementations, use @Qualifier("beanName") or @Primary to select the desired bean. @Transactional is typically placed on service‑layer methods or classes. By default, unchecked exceptions trigger rollback; you can control it with rollbackFor / noRollbackFor attributes.
Custom logic after a bean is fully initialized can be added via InitializingBean.afterPropertiesSet(), @PostConstruct, or a BeanPostProcessor.
Spring Boot embeds an embedded servlet container (Tomcat, Jetty, Undertow), so it can start an HTTP server without external deployment.
To use a non‑default configuration file, set spring.config.name or spring.config.location as a JVM argument or in application.yml. @RequestMapping (or @GetMapping / @PostMapping) accepts the method attribute to restrict HTTP verbs, e.g., @RequestMapping(value="/path", method=RequestMethod.GET).
Wrap response objects (e.g., XXResult) with @ResponseBody or return them from a @RestController so Spring’s MappingJackson2HttpMessageConverter serializes them to JSON.
Global exception handling can be done with @ControllerAdvice and @ExceptionHandler to log errors and return a unified JSON error response.
MySQL
For bulk inserts, use LOAD DATA INFILE or multi‑row INSERT statements wrapped in a single transaction.
When a query is slow, first examine the execution plan with EXPLAIN. Indexes speed up lookups by allowing the engine to locate rows without full table scans.
A single‑column index can be used for queries that reference that column plus additional columns, provided the additional columns are not used for range conditions that would invalidate the index.
For a composite index, the leftmost prefix rule applies: the index is usable if the query filters on the first column; it can also be used if the query filters on the first *n* columns in order. If only the second or third column is used, the index is ignored.
Expressions like i + 5 < 100 prevent index usage because the column is wrapped in a function; rewrite as i < 95 to allow the index.
Check index usage with EXPLAIN or SHOW STATUS LIKE 'Handler_read%' to see how many rows were read via indexes. LIKE 'aaa%' can use a B‑tree index; LIKE '%aaa%' cannot because the leading wildcard disables index lookup.
DROP removes the table definition; TRUNCATE quickly deletes all rows without logging each row deletion; DELETE removes rows row‑by‑row and can be filtered with a WHERE clause.
Database monitoring typically uses SHOW PROCESSLIST, slow‑query log, performance_schema, or external tools (Percona Toolkit, pt‑query‑digest). Slow SQL is diagnosed by examining the query plan, indexes, and I/O statistics.
MySQL’s default character set (utf8mb4) supports emoji. If the server uses utf8, convert columns to utf8mb4 or store emojis as binary blobs.
Single‑table size that degrades performance varies, but tables larger than a few hundred million rows (or >10 GB) often require partitioning or sharding.
To find a hanging query, run SHOW PROCESSLIST or
SELECT * FROM information_schema.processlist WHERE COMMAND='Query', then kill the offending thread or investigate locks.
Read‑write splitting is implemented with middleware (e.g., MySQL Proxy, ProxySQL, or HAProxy) that routes SELECTs to replicas and writes to the primary. Transactions must be pinned to the primary to avoid consistency issues.
Sharding can be done at the database or table level. Migration typically involves online data copy (pt‑online‑schema‑change, gh‑ost) and checksum verification (e.g., SELECT COUNT(*), SUM(CRC32(col)) FROM tbl on source and target).
JVM
Common GC algorithms: Serial (single‑thread, suitable for small heaps), Parallel (throughput‑oriented), CMS (low‑pause, deprecated), and G1 (predictable pause, default in JDK 9+). Choose based on latency vs. throughput requirements.
Java class loaders: Bootstrap, Extension (or Platform), and Application. They follow the parent‑delegation model: a loader first asks its parent to load a class, preventing duplicate definitions and enhancing security.
Custom class loaders override findClass to load bytecode from non‑standard sources (e.g., network, encrypted files). Use when implementing plugin systems or hot‑deployment.
PermGen (pre‑JDK 8) stored class metadata; it could cause OutOfMemoryError: PermGen space. Since JDK 8 it was replaced by Metaspace, which grows dynamically and is limited by native memory (configurable via -XX:MetaspaceSize and -XX:MaxMetaspaceSize).
During GC, objects move from Eden → Survivor → Old (or directly to Old in some collectors). The exact order depends on the collector.
OutOfMemory errors are resolved by increasing heap sizes ( -Xmx), fixing memory leaks (e.g., unbounded collections), or tuning GC thresholds.
After Java 8, Metaspace replaces PermGen. By default it expands until native memory is exhausted; you can cap it with -XX:MaxMetaspaceSize. jstack prints thread stacks; jstat reports GC statistics. To investigate GC‑related pauses, collect jstat -gcutil over time and correlate with jstack thread states. StackOverflowError occurs when recursive calls exceed the thread’s stack size. Adjust with -Xss (e.g., -Xss512k) based on expected recursion depth.
Linux Commands
View the last 100 lines of a large log: tail -n 100 /path/to/log. Continuously stream new lines: tail -f /path/to/log.
Combine tail -f with grep --line-buffered "keyword" to watch for a keyword in real time.
Case‑insensitive grep: grep -i "pattern" file. Use regular expressions with grep -E or egrep.
In vim: j moves down one line, 30j moves down 30 lines, G jumps to the end, gg returns to the top, ? searches backward.
Count word frequencies in the third column (space‑delimited):
awk '{print $3}' file | tr -s ' ' '
' | sort | uniq -c | sort -nrTo sort numerically rather than lexicographically, use sort -n (or sort -nr for descending).
Environment variables are separated by = in assignments; set them with export VAR=value (or VAR=value for a single command).
Change file mode to octal 64 (i.e., rw‑‑‑‑‑‑‑) with chmod 0640 file. The leading 6 (binary 110) gives read/write for owner.
View a process’s resource usage with top or ps -p PID -o %cpu,%mem,cmd. System load is the average number of runnable processes; on a 4‑core machine, a load of 4 is fully utilized. Press 1 in top to see per‑CPU usage.
CPU usage can exceed 100% in top because the value is per‑CPU; on a multi‑core system, 400% means full utilization of four cores.
Common performance tools: vmstat, iostat, sar, perf. Focus on CPU, memory, I/O wait, and context switches.
List open network connections of a process: lsof -p PID -i or netstat -tunp | grep PID. States of interest: ESTABLISHED, SYN_SENT, TIME_WAIT.
The kernel net.core.somaxconn (backlog) defines the maximum pending connections queue length for a listening socket.
Excessive TIME_WAIT sockets arise from normal TCP teardown. Reduce them by enabling tcp_tw_reuse and tcp_tw_recycle (Linux 2.4) or adjusting net.ipv4.tcp_fin_timeout.
TCP three‑way handshake: SYN → SYN‑ACK → ACK. To verify data sent by a library, capture packets with tcpdump -i eth0 -w capture.pcap and analyze with wireshark or tcpdump -r capture.pcap.
TCP KeepAlive sends periodic probes on idle connections to detect dead peers, reducing resource waste and improving fault detection.
Redis
Cache penetration occurs when requests for non‑existent keys bypass the cache and hit the database repeatedly. Mitigate by caching null results (with short TTL) or using Bloom filters.
Cache updates can be passive (TTL expiration) or active (write‑through/write‑behind). To avoid thundering‑herd on expiration, use a lock (e.g., Redis SETNX) or stagger TTLs.
Redis is chosen for its in‑memory speed, rich data structures, and persistence options, which many KV stores lack.
Common Java clients: Jedis, Lettuce, Redisson. High performance stems from single‑threaded I/O, pipelining, and binary protocol.
Data structures: strings, lists, sets, sorted sets (zset), hashes, bitmaps, hyperloglog. zset stores members with a score, enabling range queries by score; unlike a plain set, it maintains order.
Hash commands: HSET key field value, HGET key field, HMGET, HGETALL. LPOP removes the first element immediately; BLPOP blocks until an element is available or timeout expires. SCAN, SSCAN, HSCAN, ZSCAN iterate over collections without locking. The amount returned per call is configurable via the COUNT option and is not fixed.
Lua scripts run atomically on the server, useful for complex operations (e.g., check‑then‑set) without race conditions.
Pipeline batches multiple commands to reduce round‑trip latency. Persistence: AOF (append‑only file) logs every write for durability; RDB snapshots the dataset periodically. AOF offers better durability but larger files; RDB is faster for restarts.
Replication: a master streams write commands to replicas; BGSAVE creates an RDB snapshot in the background, which replicas can load.
When memory is insufficient, enable maxmemory-policy (e.g., allkeys-lru) or use data‑structure encodings like ziplist for small lists/hashes to reduce overhead.
ZipList is a compact sequential encoding used for small lists and hashes, saving memory by storing elements contiguously.
Monitoring & Stability
Business logs are typically collected via agents (e.g., Filebeat, Logstash) and shipped to centralized systems like Elasticsearch, Kafka, or Splunk.
Production machines are monitored with open‑source stacks (Prometheus + Grafana, Zabbix) or proprietary solutions. Metrics can be collected at second‑level granularity for latency‑sensitive services.
For a Java backend, monitor JVM metrics (heap usage, GC pauses), thread pools, response latency, error rates, and external service latency. Tools: JMX, Micrometer, Prometheus exporters, APM solutions (Pinpoint, SkyWalking).
Third‑party service calls should be instrumented (e.g., with OpenTelemetry) to capture latency, success/failure counts, and circuit‑breaker status.
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.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
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.
