Fundamentals 31 min read

Mastering Java Core Concepts: ThreadLocal, JVM Memory, GC, Concurrency, and More

This article provides a comprehensive overview of essential Java fundamentals, covering ThreadLocal, the JVM memory model, garbage collection mechanisms, synchronization primitives like synchronized and ReentrantLock, volatile semantics, concurrency utilities, thread pools, class loading, and common data structures such as HashMap and ConcurrentHashMap.

ITFLY8 Architecture Home
ITFLY8 Architecture Home
ITFLY8 Architecture Home
Mastering Java Core Concepts: ThreadLocal, JVM Memory, GC, Concurrency, and More

ThreadLocal provides a thread‑local variable copy; each thread gets its own instance stored in a map keyed by the thread object, enabling data isolation without synchronization.

The JVM memory model defines six runtime data areas: program counter (thread‑private), Java stack (thread‑private, holds local variables and operand stack), native method stack, heap (shared objects), method area (class metadata, static fields, compiled code), and runtime constant pool (per‑class constant tables).

Garbage collection occurs in the young generation (Eden and two survivor spaces) via minor GC, promoting surviving objects to the old generation; large or long‑lived objects go directly to the old generation, and Full GC is triggered when promotion would exceed old‑gen space.

Synchronized is a pessimistic, exclusive lock; ReentrantLock (a reentrant lock) offers features such as interruptible lock acquisition, multiple Condition objects, and optional fairness.

StringBuffer is thread‑safe, while StringBuilder is not; both differ in how they handle internal character arrays.

Fail‑fast behavior in Java collections throws ConcurrentModificationException when a collection is modified during iteration by another thread.

Happens‑before rules guarantee visibility: program order, monitor lock release/acquire, volatile write/read, transitivity, and thread start.

Volatile ensures visibility across threads and prevents instruction reordering, but does not provide atomicity.

Synchronization requires a task to wait for its dependencies; asynchronous execution proceeds without waiting, merely notifying dependent tasks upon completion.

CAS (Compare‑And‑Swap) is an optimistic lock that atomically updates a variable only if its current value matches an expected value.

Thread pools reuse a fixed set of worker threads to reduce creation overhead, improve response time, and simplify management; common implementations include Executors.newSingleThreadPool(), newFixedThreadPool(), newCachedThreadPool(), and newScheduledThreadPool().

Class loading follows the three phases of loading, linking (verification, preparation, resolution), and initialization, using the parent‑delegation model (bootstrap → extension → application → custom).

Consistent hashing and basic Redis data structures (String, Hash, List, Set, Sorted Set) are introduced for caching strategies.

B+‑tree indexes store key‑value pairs in leaf nodes with linked leaf pointers to accelerate range queries.

Spring IoC supports singleton, prototype, and request scopes; beans are instantiated via reflection and wired according to dependency injection configurations.

Static proxies implement the same interface as the target, while dynamic proxies (JDK or CGLIB) generate proxy classes at runtime, enabling cross‑cutting concerns such as logging and transaction management.

Spring MVC processes a request through DispatcherServlet, HandlerMapping, Controller, ModelAndView, and ViewResolver to render the response.

HTTP request flow: DNS resolution → TCP three‑way handshake → HTTP request → server response → browser renders HTML and resources.

Session stores state server‑side, identified by a JSESSIONID cookie, reducing client‑side payload compared to sending all cookies with each request.

Distributed session can be managed via Zookeeper for configuration and a shared cache (e.g., Memcached) for storage.

Adapter pattern converts one interface to another (e.g., InputStreamReader); decorator adds behavior to existing objects (e.g., BufferedInputStream).

Spring transaction configuration defines pointcuts and transaction attributes (isolation, propagation, timeout, rollback rules) using XML or @Transactional annotations.

MyBatis uses SqlSessionFactory to create SqlSession instances for executing mapped SQL statements.

Servlets handle business logic; Filters preprocess requests and postprocess responses, sharing common code across multiple servlets.

HashMap is non‑thread‑safe, allows null keys/values, and uses an array of buckets with linked lists; ConcurrentHashMap employs lock‑striping (segment locks) for high concurrency, while LinkedHashMap maintains insertion order via a doubly‑linked list.

CopyOnWriteArrayList copies the underlying array on each write, providing thread‑safe iteration at the cost of write performance, suitable for read‑heavy scenarios.

Linux commands such as cd, cp, mv, rm, ps, tar, cat, chmod, vim, find, and ls are essential for system navigation and file manipulation.

Deadlock requires mutual exclusion, hold‑and‑wait, no preemption, and circular wait; prevention, resource ordering, and the Banker's algorithm are common mitigation strategies.

Inter‑process communication mechanisms include pipes, named pipes, semaphores, message queues, signals, shared memory, and sockets.

Processes have independent address spaces and higher context‑switch cost; threads share code and data, with lower switch overhead.

Java memory: primitives and references reside on the stack; objects are allocated on the heap; static fields are stored in the method area; garbage collection reclaims unreachable heap objects.

Polymorphism is achieved via dynamic binding; method overload changes the parameter list, while method override replaces a superclass implementation in a subclass.

Abstract classes can contain constructors, fields, and concrete methods; interfaces declare abstract methods (Java 8+ can have default/static methods) and cannot hold state.

XML parsing options: DOM (memory‑intensive, tree model), SAX (event‑driven, low memory), and Pull (pull‑based event iteration).

wait() releases the object's monitor lock and allows other threads to acquire it; sleep() does not release any locks and simply pauses the current thread.

Java references: strong (prevents GC), soft (cleared under memory pressure), weak (cleared on any GC), and phantom (used for post‑finalization cleanup).

hashCode() provides a bucket index for hash‑based collections; equals() determines logical equality when hash collisions occur.

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.

JVMMemory ManagementconcurrencyspringThreadPool
ITFLY8 Architecture Home
Written by

ITFLY8 Architecture Home

ITFLY8 Architecture Home - focused on architecture knowledge sharing and exchange, covering project management and product design. Includes large-scale distributed website architecture (high performance, high availability, caching, message queues...), design patterns, architecture patterns, big data, project management (SCRUM, PMP, Prince2), product design, and more.

0 followers
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.