Introduction
Java ConcurrentModificationException occurs when collection is modified during iteration. This guide provides step-by-step diagnosis and resolution with specific commands and code examples.
Symptoms
Typical symptoms and error messages when this issue occurs:
java.lang.Error: Unexpected error occurred
at com.example.Application.main(Application.java:42)
Caused by: internal errorObservable indicators: - Application logs show errors or exceptions - JVM crashes or becomes unresponsive - Related services may fail or timeout
Common Causes
- 1.Thread concurrency issues stem from:
- 2.Improper synchronization primitives usage
- 3.Race conditions in shared state access
- 4.Missing thread safety in collections
- 5.Incorrect thread pool configuration
Step-by-Step Fix
Step 1: Check Current State
java -versionStep 2: Identify Root Cause
jcmd <pid> VM.infoStep 3: Apply Primary Fix
// Primary fix: update configuration
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
MyBean bean = new MyBean();
bean.setTimeout(30000);
return bean;
}
}Apply this configuration and restart the application.
Step 4: Apply Alternative Fix (If Needed)
// Alternative fix: use properties
# application.properties
app.timeout=30000
app.retry-count=3
app.enabled=trueRun load tests to verify thread safety under concurrent access.
Step 5: Verify the Fix
After applying the fix, verify with:
java -jar application.jar --debugExpected output should show successful operation without errors.
Common Pitfalls
- Not reading error messages carefully
- Applying fixes without understanding root cause
- Skipping verification after changes
Best Practices
- Read official documentation first
- Test in isolated environment
- Document changes for team visibility
Related Issues
- Java OutOfMemoryError
- Java StackOverflowError
- Java ClassNotFoundException