← All topics

Concurrency

Threads, volatile, synchronized, locks and atomic classes.

100 questions

Start ▶
Level:
1 What is the difference between a process and a thread? A process is a separate program started by the operating system, with its own memory. A thread is a separate path of execution inside a process: threads in one process share the heap, but each has its own stack. Junior 2 What ways are there to start a new thread in Java? Extend Thread, pass a Runnable to new Thread(...), submit a Callable to an ExecutorService, or, in Java 21, Thread.ofVirtual().start(...). In practice you almost always use an executor. Junior 3 What happens if you call run() instead of start() on a Thread? run() executes as an ordinary method on the current thread, and no new thread is created. A new thread appears only when start() is called, and it calls run() on its own. Junior 4 What states does a thread go through, and where can you see them? Thread.State has six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. You see them through getState() or in a thread dump (jstack). Junior 5 What is a race condition? Show it with a simple example. When the result depends on the order in which threads run, that is a race condition. The classic example is two threads running the same count++, and some increments get lost. Junior 6 What does the synchronized keyword actually do? It acquires the object's monitor: only one thread at a time can enter the code guarded by that monitor. On top of that, changes made before leaving the block become visible to the next thread that enters. Junior 7 What is a volatile variable for? volatile guarantees that a write is immediately visible to other threads, and it forbids the compiler from reordering around that variable. But it does not make operations atomic. Junior 8 What is the difference between Thread.sleep() and Object.wait()? Thread.sleep(ms) / obj.wait() — Belongs to: a static method of the Thread class / a method of Object; Where it is called: anywhere / only while holding the obj monitor; Lock: keeps it / releases it; Wakes up: after the time passes or on interrupt() / on notify/notifyAll, timeout, interrupt() Junior 9 What is the join() method used for? t.join() makes the current thread wait until t finishes. There is a timed version too: join(millis), or join(Duration) in Java 19+. Junior 10 What is a daemon thread, and how does it differ from a regular thread? A daemon thread is a "background" thread. The JVM waits only for the non-daemon threads to finish; when they are done, daemon threads are stopped midway and the process exits. Junior 11 What is a deadlock, and how does it come about? When two or more threads each wait for a lock held by the other and stand still forever, that is a deadlock. It usually appears when locks are acquired in different orders. Junior 12 Why should you use an ExecutorService instead of new Thread() for each task? Creating and destroying threads is expensive, and if their number is unbounded, memory and CPU run out. An executor reuses threads, limits their number, provides a queue, and returns the result through a Future. Junior 13 What is the difference between the Runnable and Callable interfaces? Runnable.run() returns nothing and can't throw a checked exception. Callable.call() returns a result and may throw Exception. It is usually used with ExecutorService.submit(). Junior 14 What is a Future, and what should you watch out for when working with its get() method? A Future is a "ticket" for the result of a computation that hasn't finished yet. get() blocks the current thread until the result is ready, so it is usually called with a timeout. Junior 15 What is better about AtomicInteger than a plain int? AtomicInteger performs read-modify-write operations atomically through CAS, without locks. So even when many threads increment it, not a single value is lost. Junior 16 What do you choose instead of HashMap where several threads are involved, and why? ConcurrentHashMap. HashMap is not thread-safe: with parallel writes, data is lost or the structure gets corrupted. Collections.synchronizedMap works, but it makes everything sequential with a single lock. Junior 17 What does it mean for a class to be "thread-safe", and how do immutable objects help with that? A thread-safe class works correctly when several threads use it at the same time, without extra synchronization. An immutable object never changes its state, so it is automatically thread-safe. Junior 18 How do you stop a thread the right way? How does interrupt() work? Thread.stop() is dangerous and no longer works since Java 20. The right way is interrupt(): it sets a "stop" flag on the thread, and the thread has to check it itself and exit cleanly. Junior 19 What is ThreadLocal, and when is it used? ThreadLocal stores a separate value for each thread: one variable, but every thread sees its own copy. It is mostly used for request context (user, trace id) or for objects that are not thread-safe. Junior 20 What is a virtual thread in Java 21, and how does it differ from a regular thread? A virtual thread is a lightweight thread managed by the JVM. It sits on an OS thread only while it is running, and frees it while waiting for I/O. So you can open millions of virtual threads. Junior 21 Do a static synchronized method and a regular synchronized method block each other? No. An instance method takes the monitor of the this object, while a static method takes the monitor of the Klass.class object. These are two different locks, so they can run in parallel. Strong Junior 22 Why should you always call wait() inside a while loop, not an if? A thread can wake up even without a notify (a spurious wakeup), or by the time it wakes up, another thread has already changed the condition. while re-checks the condition after waking up. Strong Junior 23 Why does this counter give a wrong result even though it is volatile? volatile guarantees only visibility, while count++ is three separate operations: read, add, write. Two threads read the same old value and overwrite each other. Strong Junior 24 What is the difference between shutdown() and shutdownNow() in ExecutorService? shutdown() stops accepting new tasks, but finishes the queued and running ones. shutdownNow() drains the queue, returns the list of tasks that never ran, and sends an interrupt to the running threads. Strong Junior 25 Why does an exception in a task sent with submit() not show up in the log? submit() catches the exception and stores it inside the returned Future. If nobody calls get(), the error quietly disappears. execute(), on the other hand, passes the exception to the thread's UncaughtExceptionHandler. Strong Junior 26 When is CopyOnWriteArrayList the right choice, and when is it a bad one? It copies the whole array on every write, while reads and iteration are lock-free. So it is great for small lists with lots of reads and very few writes, such as a list of listeners. Strong Junior 27 Does ConcurrentModificationException only appear with multiple threads? No, it often appears on a single thread: when you iterate a collection with for-each and modify it directly. This is the "fail-fast" iterator's check and has nothing to do with thread safety. Strong Junior 28 Why is it a mistake to catch InterruptedException and leave the catch block empty? When the exception is thrown, the interrupt flag is cleared. If you swallow it, the code above and the executor never find out that a stop was requested, and as a result the service doesn't shut down or the task isn't cancelled. Strong Junior 29 What are the hidden dangers of Executors.newFixedThreadPool and newCachedThreadPool? A fixed pool uses an unbounded LinkedBlockingQueue, so if load grows, the queue grows without limit and memory runs out. A cached pool doesn't limit the thread count, so it opens a new thread for every new task and can choke the OS. Strong Junior 30 How do you build producer-consumer with a BlockingQueue? The producer puts items in with put() and the consumer takes them with take(). If the queue is full, the producer waits automatically, and if it is empty, the consumer waits, so there is no need to write wait/notify by hand. Strong Junior 31 What does ReentrantLock do better than synchronized, and when do you choose it? ReentrantLock offers tryLock (with a timeout), lockInterruptibly, a fair mode, and several Conditions. If you don't need these, synchronized is simpler and safer, because you can't forget to unlock. Middle 32 How does ReadWriteLock work, and when does it really give you speed? Many threads can hold the read lock at the same time, while the write lock is exclusive. It helps where reads are frequent, writes are rare and the reads take a relatively long time; for short operations it can even be slower than a plain lock. Middle 33 In CompletableFuture, how do thenApply, thenCompose and thenCombine differ? thenApply transforms the result with a plain function. thenCompose is used when the next step itself returns a CompletableFuture, and it "flattens" the nested future. thenCombine merges the results of two independent futures. Middle 34 How do you catch an error in a CompletableFuture chain: what is the difference between exceptionally, handle and whenComplete? exceptionally runs only on error and returns a fallback value. handle is always called and can change both the result and the error. whenComplete is also always called, but doesn't change the result; it is for logging and metrics. Middle 35 In what situations are CountDownLatch, CyclicBarrier and Semaphore used? CountDownLatch: one or more threads wait for N jobs to finish, one time only. CyclicBarrier: N threads wait for each other at a point, and it is reusable. Semaphore: limits how many threads can access a resource at the same time. Middle 36 How do ThreadPoolExecutor's core, max, queue and rejection settings work together? When a new task arrives: if there are fewer threads than core, a new thread is started; otherwise it goes into the queue; if the queue is full, new threads are started up to max; if that is full too, the rejection policy applies. It is not "threads up to max first, then the queue", as most people expect. Middle 37 What traps can you run into when using @Async in Spring? The most common ones: an @Async method called from inside the same class runs synchronously (the proxy is bypassed), if you don't configure an executor the default pool isn't what you expect, errors from void methods disappear, and ThreadLocal context doesn't carry over to the new thread. Middle 38 With thread pools, how does ThreadLocal lead to a memory leak and mixed-up data? Threads in a pool don't die, so a value that was never remove()d gets "inherited" by the next task. If the value is a large object or a reference to a class loader, it stays in memory forever. Middle 39 On prod the app "hung". How do you determine whether it is a deadlock? I take a thread dump: jstack <pid>, jcmd <pid> Thread.print, or Actuator's /threaddump endpoint. The JVM finds monitor and ReentrantLock deadlocks on its own and writes "Found one Java-level deadlock" at the end of the dump. Middle 40 What breaks in double-checked locking if there is no volatile? Another thread may see instance != null while the object isn't fully constructed yet, because the writes inside the constructor and the write of the reference can be reordered. volatile guarantees both the ordering and the visibility. Middle 41 What is the happens-before relationship in the Java memory model, and which operations create it? Happens-before is the guarantee that "all of A's writes are visible to B, and A is ordered before B". It arises through operations like releasing/acquiring a monitor, a volatile write/read, Thread.start/join, and submitting to an executor, and it is transitive. Strong Middle 42 How does StampedLock's optimistic read mode work, and what are its dangers? tryOptimisticRead() takes no lock and only returns a "stamp". After reading, validate(stamp) checks that no write happened in between; if one did, you re-read with a regular read lock. It is fast, but not reentrant and easy to misuse. Strong Middle 43 What is virtual thread "pinning", and what problem does it cause in Java 21? Pinning is when a virtual thread blocks and can't come off its carrier thread, so it keeps the carrier occupied. In Java 21 this happens when it blocks inside a synchronized block or a native method; since there are few carriers, the whole application can grind to a halt. Strong Middle 44 When very many threads increment one counter, why is LongAdder faster than AtomicLong? In AtomicLong, all threads fight with CAS over a single memory cell and retry a lot. LongAdder spreads the sum over several cells when contention appears, and sum() adds them up. Writes are fast, but a read is not an exact "instantaneous" value. Strong Middle 45 Why is it dangerous to do blocking I/O inside CompletableFuture.supplyAsync? If you don't pass an executor, the task runs in ForkJoinPool.commonPool(). It is one pool for the whole JVM and it is small (number of cores minus 1). Blocking calls fill it up, and parallel streams and other async code stall too. Strong Middle 46 What is the ABA problem in a CAS operation, and when is it a real risk? CAS only checks "is the value still A?". If another thread changed the value A→B→A in between, CAS doesn't notice. In lock-free stacks or structures that reuse objects, this can corrupt the structure. Strong Middle 47 How do livelock and starvation differ from deadlock? Give an example of each. In a deadlock, threads wait and stand still. In a livelock they are actively working, changing state by yielding to each other, but they make no progress. In starvation, the system is running, but some threads never get the resource. Strong Middle 48 What happens if you do something slow, or something that touches the same map, inside ConcurrentHashMap.computeIfAbsent? The mapping function runs under the bucket lock. A slow function also blocks the other keys that land in the same bin, and modifying that same map from inside gives an IllegalStateException, or even an infinite loop in some versions. Strong Middle 49 What is safe publication, and what does letting this escape from a constructor lead to? Safe publication is a way of handing over an object that guarantees another thread sees it fully constructed. If this is registered as a listener or given to a thread inside the constructor, another thread may see fields that haven't been filled in yet. Strong Middle 50 How does work-stealing in ForkJoinPool work, and when should you not use a parallel stream? Each worker has its own deque: it takes its own tasks from one end, and a worker that runs out of work "steals" from the other end of another's deque. That is great for divisible CPU work, but for blocking I/O or small data, a parallel stream does harm, not good. Strong Middle 51 How does LockSupport.park/unpark work, and how do locks like ReentrantLock rely on it internally? park() puts the current thread to sleep until a "permit" is available, and unpark(t) hands that thread one permit. AQS, which sits under ReentrantLock, Semaphore and CountDownLatch, changes its state with CAS, queues the waiters, and puts them to sleep and wakes them with exactly park/unpark. Strong Middle 52 This Spring service works fine in tests, but in prod it sometimes returns another customer's data. Why? Spring beans are singletons by default, so one object is shared by all request threads. Because currentUser is an instance field, concurrent requests overwrite each other's value. Request-specific state has to live in a parameter or a local variable. Strong Middle 53 How does a synchronized block work internally, and how does the JVM change lock states? Every object has a mark word in its header, and synchronized takes the monitor there. Without contention, a thin lock is acquired with CAS; as contention grows, it moves to a heavy OS-level monitor (inflated). Strong Middle 54 How do the fair and non-fair modes of ReentrantLock differ, and which one would you pick? A fair lock lets waiters through in queue order, while a non-fair lock lets a newly arrived thread "snatch" a lock that has just been released. Non-fair is usually much faster, and fair protects against starvation. Strong Middle 55 How does Condition differ from wait/notify, and what do multiple Conditions on one lock give you? Condition gives one lock several wait queues and works with ReentrantLock, while wait/notify gives a monitor a single queue. The condition is checked in a while loop, because of spurious wakeups and because another thread can break the condition again. Strong Middle 56 How is ConcurrentHashMap structured internally in Java 8 and later? There are no segments: an empty bucket is written with CAS, and in an occupied bucket only the first node of that bucket is locked. Reads are lock-free, a long chain turns into a tree, and several threads can do a resize together. Strong Middle 57 Why use ThreadLocalRandom instead of Random in multithreaded code? java.util.Random is thread-safe, but on every call it updates its internal seed with CAS on a single AtomicLong, and with many threads that spot becomes a bottleneck. ThreadLocalRandom keeps separate state per thread, so there is no contention. Strong Middle 58 In prod we got "OutOfMemoryError: unable to create native thread". What does it mean and how do you find the cause? This is not a full heap: the OS or the container refused to create a new thread. The cause is usually a thread leak (executors that were never shut down, an unbounded cached pool), a pids or ulimit -u limit, or not enough native memory for the stacks. Strong Middle 59 How do scheduleAtFixedRate and scheduleWithFixedDelay differ in ScheduledExecutorService, and what happens if the task throws an exception? FixedRate runs the task on a strict schedule by start times, while FixedDelay runs it with a set pause after the previous run finishes. With both, if the task throws, all later runs are silently cancelled. Strong Middle 60 In Spring I have several @Scheduled methods, and when one of them gets slow, the others are delayed too. Why? By default Spring Boot creates a single-threaded ThreadPoolTaskScheduler for scheduling. All @Scheduled methods run on that one thread in turn, so one long task blocks the rest. You need to increase the pool size or move the heavy work to a separate executor. Strong Middle 61 On which thread do thenApply and thenApplyAsync run in CompletableFuture? thenApply runs on the calling thread if the previous stage has already finished, and if it hasn't, on the thread that completes it. thenApplyAsync is always submitted to an executor, and if you don't pass one, to ForkJoinPool.commonPool(). Strong Middle 62 How do you collect the results of several requests with CompletableFuture.allOf, and what happens if one of them fails? allOf returns a CompletableFuture<Void>, so you get the results with join() on each future separately. If one fails, allOf also ends with an error, but only after all of them have finished, and the remaining requests are not cancelled. Strong Middle 63 What happens to the transaction and the EntityManager if you split the work inside a @Transactional method across several threads? The transaction and its bound EntityManager/connection are tied to the current thread through ThreadLocal. A new thread doesn't see them: it runs outside the outer transaction, and the EntityManager itself is not thread-safe, so you can't share it between threads. Strong Middle 64 In prod a Java service is eating 100% CPU. How do you find which thread and which code is to blame? First I get the IDs of the threads using the most CPU at the OS level (top -H), convert them to hex and match them with nid in a thread dump. A few dumps, or async-profiler's CPU flame graph, will show the exact method. Strong Middle 65 When would you pick ArrayBlockingQueue, LinkedBlockingQueue or ConcurrentLinkedQueue? If threads need to wait (producer-consumer), use a blocking queue: ArrayBlockingQueue for a strict capacity and few allocations, a bounded LinkedBlockingQueue for higher throughput. If nobody should wait or block, use the lock-free ConcurrentLinkedQueue. Strong Middle 66 How does DelayQueue work, and when can you use it for delayed retries? DelayQueue is a blocking queue whose elements implement the Delayed interface: an element comes out of take() only after its time is up. It's handy inside one JVM for things like "retry in 5 seconds", but everything is lost on a restart. Strong Middle 67 Why is SynchronousQueue called a "zero-capacity" queue, and where is it used? SynchronousQueue stores nothing: a thread that does put waits until someone does take. It's a hand-to-hand handoff. Its best-known use is in newCachedThreadPool: a task is given to an idle thread right away, and if there's no idle thread, a new one is started. Strong Middle 68 What do you use when you need a sorted Map in multithreaded code? How does ConcurrentSkipListMap work? TreeMap is not thread-safe, and Collections.synchronizedSortedMap makes everything go through one lock, one at a time. ConcurrentSkipListMap is based on a lock-free skip list, keeps keys in order, and runs get, put and range queries in parallel in O(log n) on average. Strong Middle 69 When does busy-waiting (spinning) pay off, and what does Thread.onSpinWait() give you? Spinning means a thread doesn't sleep but checks the condition over and over in a loop. If the wait is very short (under a microsecond), it's cheaper than park/unpark. Thread.onSpinWait() gives the processor a hint that "I'm spinning" (PAUSE on x86), which helps with power use and with the neighboring hyper-thread. Strong Middle 70 I need an atomic counter in each of millions of objects. Why would you choose AtomicLongFieldUpdater or VarHandle over an AtomicLong field? Every AtomicLong is a separate object: a header, a reference and an extra indirection. A field updater or a VarHandle does CAS on a plain volatile long field, so it saves memory and follows one reference fewer. The price is more complex code that's easier to get wrong. Strong Middle 71 How do virtual threads in Java 21 work internally, and when do they really help? A virtual thread is a lightweight thread managed by the JVM: on a blocking operation it "steps off" the carrier (platform) thread, its stack is saved to the heap, and the carrier picks up other work. The benefit comes in services with a lot of IO waiting and thousands of concurrent requests, not in CPU-bound work. Senior 72 What happens when a CPU-heavy task runs for a long time on virtual threads? Does the scheduler forcibly switch it out? No, the virtual thread scheduler doesn't do time-slicing: a virtual thread frees its carrier only when it blocks or finishes. Heavy computation on as many threads as there are cores can take over all the carriers and raise the latency of the thousands of other IO threads. CPU work has to be moved to a separate, bounded platform pool. Senior 73 How do you store a set of rules that is read hundreds of thousands of times per second but rarely updated, across threads? An immutable snapshot plus a single volatile reference (or an AtomicReference): readers take the current snapshot without a lock, and the writer builds a complete new copy and swaps the reference in one step. Reads are nearly free, and consistency is guaranteed at the level of the whole snapshot. Senior 74 What is false sharing, how does it affect performance, and how do you detect it? Two threads write to logically separate variables, but those variables sit in the same 64-byte cache line. Every write invalidates the whole line in the other core's cache, and the code slows down even though it's parallel. Senior 75 How do you calculate a thread pool size, and how do you verify that decision? For CPU-bound work it's around the number of cores; for IO-bound work you start from the formula cores × (1 + wait/compute) or from Little's law. But that's only a starting point: the final value is set by load testing and by downstream limits. Senior 76 How do you build backpressure at the thread pool level in an asynchronous processing system? The main idea is to give up the unbounded queue: a bounded queue, CallerRunsPolicy or an explicit rejection when it's full, and a Semaphore to limit the number of concurrent jobs. That way load slows down the producer, not the memory. Senior 77 How do you shut down an ExecutorService gracefully, especially in Kubernetes? First you stop accepting new tasks with shutdown(), wait for a bounded time with awaitTermination, then send an interrupt with shutdownNow(). The whole process has to be shorter than the pod's terminationGracePeriodSeconds. Senior 78 What is structured concurrency, and what problem is StructuredTaskScope trying to solve? Structured concurrency is the idea that parallel subtasks can't "escape" the lexical block of their parent task: when the block ends, every child has finished or been cancelled. In Java 21, StructuredTaskScope shipped as a preview API, and it keeps changing in later versions. Senior 79 How do you measure lock contention in prod, and what techniques do you use to reduce it? JFR's jdk.JavaMonitorEnter/jdk.ThreadPark events or async-profiler's lock mode show which lock is waited on and for how long. To reduce it: shorten the critical section, use lock striping, an immutable snapshot, a lock-free structure, or split the work by thread. Senior 80 The service runs on two instances and one order got paid twice. Why didn't synchronized help, and what do you do? synchronized only coordinates threads inside one JVM, and a thread in the second pod can't see it at all. The fix has to live in a shared resource: a unique constraint or a conditional UPDATE in the DB, an optimistic version, and if needed a distributed lock and an idempotency key. Senior 81 What does the Java Memory Model guarantee and not guarantee in a program with a data race? For a program without data races, the JMM gives sequential consistency: the code looks as if it ran in order. If there is a race, only a minimal guarantee remains: values never appear "out of thin air" and safety isn't broken, but the order and visibility of reads can't be predicted. Staff 82 How do you safely use a legacy library that isn't thread-safe (for example, a vendor SDK client) in a high-load service? First I find out from the docs and the code whether the object is not thread-safe at all or only partly. Then I pick an option: a separate instance per call or per thread, a bounded pool of objects, or confining it to one thread. The last resort is a separate process. Staff 83 How do the plain, opaque, acquire/release and volatile access modes in VarHandle differ, and when do you need them? They form a ladder of guarantee strength: plain gives no ordering, opaque gives coherence for a single variable, acquire/release gives pairwise happens-before, and volatile gives one common order for everything. The weaker the mode, the cheaper it is, and the easier it is to get wrong. Staff 84 How do you plan a migration of a large monolith from platform threads to virtual threads? First I measure where there is a benefit: the share of IO waiting, thread pool queues. Then I look for obstacles (pinning, heavy reliance on ThreadLocal, hidden limits imposed by pools) and roll it out step by step, behind a feature flag, verified by load testing. Staff 85 10,000 virtual threads run at once, and the DB connection pool has 50. What happens, and how do you design the system? The virtual threads pile up in Hikari's queue waiting for a connection, errors start after connectionTimeout, and the DB still never sees more than 50 queries. You need to limit concurrency at the entry point, cut the work done in the DB, and align the timeouts across the layers. Staff 86 How do you choose between WebFlux (reactive) and virtual threads for a new high-load service? On Java 21+, for most IO-bound services, virtual threads with plain blocking code are simpler and enough. The reactive stack pays off for streaming, streams that need backpressure, long-lived connections (SSE, WebSocket), and when the team already has a reactive ecosystem. Staff 87 What is ScopedValue, and in what ways is it better than ThreadLocal? ScopedValue passes a value down a chain of calls for the duration of a block, and it disappears on its own when the block ends. It's immutable, it's inherited cheaply by child threads, and it's much lighter than ThreadLocal when there are many virtual threads. It was a preview in Java 21 and became final in JDK 25. Staff 88 When is it worth writing a lock-free data structure yourself? Explain with the Michael-Scott queue as an example. Almost never in business code: in the JDK, ConcurrentLinkedQueue is built on exactly the Michael-Scott algorithm. Writing your own is worth it when the profiler shows clear contention, the existing structures don't fit, and you have time to verify with jcstress. Staff 89 How do you correctly propagate MDC, the trace ID and the security context through CompletableFuture and thread pools? These contexts live in ThreadLocal and don't cross to another thread on their own. The fix is a wrapper that captures the context when the task is submitted, restores it when it runs, and cleans up at the end: TaskDecorator in Spring, ContextSnapshot/context-propagation in Micrometer, Context.wrap in OpenTelemetry. Staff 90 One service calls several external systems, and when one of them slows down everything stops. How do you design a bulkhead at the thread level? Each external dependency gets its own bounded resource, a separate thread pool or a semaphore. That way a slow dependency uses up only its own share, and the other endpoints keep working. Staff 91 How do you test concurrency bugs? Why isn't an ordinary unit test enough, and what does jcstress give you? A unit test checks one interleaving, while the bug hides in an ordering that shows up one run in a million. jcstress is an OpenJDK tool: it runs a small piece of code in parallel millions of times, counts all the outcomes it sees, and flags the unexpected ones. On top of that come stress tests, static analysis and simple design. Staff 92 When a cache entry expires, hundreds of threads recompute the same expensive value at once. How do you solve this inside the JVM? This is a cache stampede: for one key only one thread should compute, and the others should wait for its result. I do it with request coalescing through ConcurrentHashMap<K, CompletableFuture<V>>, Caffeine's refreshAfterWrite, and adding jitter to the expiry. Staff 93 This code was supposed to run operations for one account one after another, but the balance still gets corrupted. What's wrong? synchronized (Long.valueOf(accountId)) takes a lock on a boxed Long. Outside the range -128..127, every autoboxing creates a new object, so threads take different monitors and there's no protection. With small IDs it's the opposite: you share one cached object with unrelated code. Staff 94 What is thread starvation deadlock? What happens when a task in a pool submits a new task to the same pool and waits for its result? All threads in the pool are busy waiting for the results of inner tasks, and the inner tasks sit in the queue waiting for a free thread, so nobody moves forward. The JVM doesn't report this as a deadlock, but the service freezes completely. Staff 95 How do timeouts and cancellation work in CompletableFuture, and what resource leaks can they cause? orTimeout and completeOnTimeout only complete the future, and the work behind it doesn't stop. cancel(true) doesn't interrupt the running thread either. So real cancellation comes from passing the timeout to the lower layer (the HTTP client, JDBC) or from making the work stoppable by yourself. Staff 96 Operations on one account must run in strict order and without locks. How do you design a single-writer or partitioning approach? Each key (for example, an account ID) is permanently assigned by hash to one executor: a single thread or a single queue. Then order within one key is preserved naturally, no shared lock is needed, and different keys run in parallel. Staff 97 When I added threads, the system got slower instead of faster. How do Amdahl's law and the Universal Scalability Law explain this? Amdahl's law: the sequential part of the code sets the limit on speedup. USL adds a coherency cost to that: the time threads spend coordinating shared state grows quadratically with the thread count, so past a certain point throughput drops. Staff 98 After we moved from x86 servers to ARM servers (for example, Graviton), some results started coming out wrong. What do you suspect from a concurrency standpoint? x86 has a strong memory model (TSO) and "forgives" a lot of code that violates the JMM. ARM reorders writes and reads much more freely. So flags without volatile, objects that weren't safely published, and hand-written lock-free code are the first suspects. Staff 99 One JVM has Tomcat, Hikari, @Async, a Kafka consumer and HTTP client pools. How do you plan the thread and concurrency budget for the whole application? You look at the pools not one by one but as a single chain: which pools an incoming request passes through, where it waits, and which resource is the narrowest. The pools are sized from that narrowest resource, from the inside out, and everything is visible in metrics. Staff 100 How do you design a high-load rate limiter (token bucket) inside one JVM that doesn't use locks? I keep the state in one immutable object (the token count and the last refill time) and update it with a CAS loop on an AtomicReference. It's lock-free and correct, but under very high contention CAS retries pile up. In that case, splitting by key or using a ready-made library is better. Staff