In Java, if you start multiple threads on the same object or variable, it is possible to throw and exception without security
Java.util.ConcurrentModificationException
This exception is thrown when the method detects concurrent modifications to an object but does not allow this modification (concurrency exception)
Workaround:
- Add volatile before the object/variable. A volatile-modified member variable forces the value of the member variable to be reread from shared memory each time it is accessed by the thread. Also, when a member variable changes, forcing the thread to write the change back to the shared memory. So at any moment, two different threads always see the same value for a member variable. The Java language specification states that for optimal speed, a thread is allowed to save a private copy of a shared member variable, and is compared to the original value of a shared member variable only if the thread enters or leaves the synchronized code block. This way, when multiple threads interact with an object at the same time, it is important to notice that the thread gets the changes to the shared member variables in a timely manner. The volatile keyword is a hint to the JVM that the member variable cannot hold its private copy, but should interact directly with the shared member variable. Usage Recommendation: Use volatile on member variables accessed by two or more threads. You do not have to use the variable you want to access when it is already in a synchronized code block, or is a constant. It is inefficient to use volatile to mask the necessary code optimizations in the JVM, so use this keyword when necessary.
- Add the object/variable to the lock synchronized adornment. In the thread, use the synchronization method or the synchronization block.
- Use threads with thread safety. Such as: Inherit the TimerTask class implementation thread, start the thread with Timer.schedule .
Understanding of multi-threaded access to the same variable (concurrent access) in Java