


Data inconsistency problem and solution for ConcurrentHashMap in concurrent environment
Aug 17, 2025 am 06:33 AMProblem analysis
In the original code, ExecutorService executes System.out.println(map.size()) immediately after submitting the task. Since threads in the thread pool are executed concurrently, the main thread will not wait for all child threads to complete the put operation. Therefore, the result of map.size() may be smaller than expected.
Solution: Use ExecutorService.invokeAll()
To ensure that all threads have completed the write operation before reading the size of the ConcurrentHashMap, you can use the ExecutorService.invokeAll() method. This method blocks the main thread until all submitted tasks are executed.
The following is the modified code:
import java.util.Map; import java.util.Collections; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Callable; public class ConcurrentHashMapExample { public static void main(String[] args) throws InterruptedException { Map<integer integer> map = new ConcurrentHashMap(); Runnable runnable = () -> { for (int i = 0; i <p> <strong>Code explanation:</strong></p> <ol> <li> <strong>Collections.nCopies(4, Executors.callable(runnable))</strong> : Creates a collection of 4 Callable objects, each Callable object wraps the runnable. The Executors.callable() method converts Runnable to Callable.</li> <li> <strong>executorService.invokeAll(...)</strong> : Submit Callable collection to thread pool. The invokeAll() method blocks the current thread until all tasks are executed.</li> <li> <strong>System.out.println(map.size())</strong> : Print the size of ConcurrentHashMap after all threads have completed writing.</li> </ol> <p> <strong>Notes:</strong></p> <ul> <li> After using ExecutorService, be sure to call the executorService.shutdown() method to close the thread pool and free up resources.</li> <li> The invokeAll() method will throw an InterruptedException exception and need to be processed.</li> </ul> <h3> Summarize</h3> <p> By using the ExecutorService.invokeAll() method, you can ensure that all threads have completed the write operation before reading the size of the ConcurrentHashMap, thus avoiding the problem of data inconsistency. This method is suitable for scenarios where you need to ensure that all concurrent tasks are completed before subsequent processing is performed. In concurrent programming, it is crucial to understand the execution order and synchronization mechanism of threads. Choosing the right tools and methods can effectively avoid potential problems.</p></integer>
The above is the detailed content of Data inconsistency problem and solution for ConcurrentHashMap in concurrent environment. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

Optional is a container class introduced by Java 8. It is used to clearly indicate that a value may be empty, thereby avoiding NullPointerException; 2. It simplifies nested null checking by providing map, orElse and other methods, preventing methods from returning null and standardizing collection return values; 3. Best practices include only returning values, avoiding the use of fields or parameters, distinguishing orElse from orElseGet, and not calling get() directly; 4. Optional should not be abused. If non-empty methods do not need to be wrapped, unnecessary Optional operations should be avoided in the stream; correct use of Optional can significantly improve code security and readability, but it requires good programming habits.

PrepareyourapplicationbyusingMavenorGradletobuildaJARorWARfile,externalizingconfiguration.2.Chooseadeploymentenvironment:runonbaremetal/VMwithjava-jarandsystemd,deployWARonTomcat,containerizewithDocker,orusecloudplatformslikeHeroku.3.Optionally,setup
