Understanding Distributed Locks, Session Management, Maven Configuration, and Caching in Backend Architecture

This article explains the fundamentals of backend architecture, covering Maven's settings.xml, front‑back separation, various types of locks (thread, process, distributed), detailed Redis‑based and Zookeeper‑based distributed lock implementations with code examples, session handling in distributed systems, and key Spring‑Redis caching annotations.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Understanding Distributed Locks, Session Management, Maven Configuration, and Caching in Backend Architecture

Architecture Overview

Front‑back separation is introduced, accompanied by illustrative diagrams.

settings.xml : Maven's global configuration file, which defines local repository locations, remote repository servers, and authentication information, while pom.xml provides project‑specific configuration.

Maven stores JAR packages in a repository, allowing projects to reference them without copying files.

Note: This "repository" refers to the Repository folder under the local Maven installation directory.

Distributed Locks

Thread lock : Only one thread can execute a locked code block within the same JVM (e.g., synchronized).

Process lock : Controls access to a shared resource among multiple processes on the same operating system.

Distributed lock : Controls resource access across multiple processes on different machines.

Three common implementations:

Database optimistic lock

Redis‑based distributed lock

Zookeeper‑based distributed lock

Optimistic lock : Uses a version field to detect conflicts; if versions differ, the operation can be retried or discarded.

Redis‑Based Distributed Lock (used in this system)

Basic commands:

SETNX – set key only if it does not exist.

GETSET – get the old value and set a new one atomically.

EXPIRE – set a TTL for a key.

Lock acquisition example (Jedis is the Java client for Redis):

jedis.set(String key, String value, String nxxx, String expx, int time)

Incorrect lock pattern 1 (deadlock if the program crashes after setnx and before setting expiration):

Long result = jedis.setnx(Key, value);
if (result == 1) {
    // If the program crashes here, expiration is never set → deadlock
    jedis.expire(Key, expireTime);
}

Incorrect lock pattern 2 (requires synchronized clocks across clients):

long expires = System.currentTimeMillis() + expireTime;
String expiresStr = String.valueOf(expires);
if (jedis.setnx(lockKey, expiresStr) == 1) {
    return true;
}
String currentValueStr = jedis.get(lockKey);
if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) {
    String oldValueStr = jedis.getSet(lockKey, expiresStr);
    if (oldValueStr != null && oldValueStr.equals(currentValueStr)) {
        return true;
    }
}
return false;

Unlocking is done by verifying the lock owner and calling jedis.del(lockKey).

Zookeeper‑Based Distributed Lock

Zookeeper provides a hierarchical namespace of znodes. Clients create an ephemeral sequential node under a designated locker node; the client that holds the smallest sequence number acquires the lock.

Lock acquisition steps:

Create an ephemeral sequential node under locker.

List all children of locker.

If the created node has the smallest sequence number, the lock is obtained.

Otherwise, watch the node that is immediately before yours; when it is deleted, repeat the check.

When the lock is released, the client deletes its temporary node.

Session Management in Distributed Systems

In a distributed environment, multiple nodes handle requests, so a user's session may be routed to different servers, causing session loss.

Common solutions:

Store sessions in Redis; each server retrieves session data from Redis.

Use IP‑hash load balancing so that the same client IP is consistently routed to the same server.

As long as the browser is not restarted, the session identifier remains consistent across short‑lived HTTP requests.

Redis as a Distributed Lock and Cache

High concurrency is handled by designing the system to process many requests in parallel. Java synchronization (e.g., synchronized, ReentrantLock) ensures thread‑safe access to shared resources.

Spring cache annotations: @Cacheable – caches the method result on first execution. @CachePut – always executes the method and updates the cache.

Database Locking

Optimistic lock uses a version field; pessimistic lock can be achieved with SQL such as:

select * from account where name="Erica" for update

Hibernate example for row‑level locking:

String hql = "from TUser as user where user.name='Erica'";
Query query = session.createQuery(hql);
query.setLockMode("user", LockMode.UPGRADE);
List userList = query.list();

Java Collections Overview

List implementations (ArrayList, LinkedList, Vector) are ordered, allow duplicates and nulls.

Set implementations are unordered and do not allow duplicate elements; HashSet relies on hashCode() and equals() for uniqueness.

Using a Set can remove duplicates from a List. HashMap stores key‑value pairs, resolves collisions via linked lists or red‑black trees, and expands when the load factor exceeds 0.75.

Source code repository: https://github.com/923310233/wxOrder

End of article – readers are encouraged to share and join the architecture community.

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.

BackendJavaredisZooKeeperSessiondistributed-lock
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

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.