BradWalker commented on PR #9818:
URL: https://github.com/apache/netbeans/pull/9818#issuecomment-7057198729

   Here is what Google AI said about this issue..
   
   ```
   `the bug is a cross-thread race condition between wrap() and close().
   
   Root Cause
   
   1. UndoableWrapper is registered globally via @MimeRegistration(mimeType="", 
service=UndoableEditWrapper.class) and uses an AtomicBoolean active 
flag—meaning it is designed to intercept document edits across threads.
   2. docToFirst is a plain, unsynchronized HashMap.
   3. In RefactoringSession.reallyDoRefactoring(), close() is called before 
setActive(false, null) (or while active.get() is still true on another thread).
   4. While the refactoring thread is iterating docToFirst.values() inside 
close(), a background thread (such as the NetBeans Java indexer, parser, or 
BeforeSaveTasks cleanup) edits an open BaseDocument, triggering wrap(), which 
calls docToFirst.put(...) on the unsynchronized HashMap and throws 
ConcurrentModificationException.
   
   How to Fix It
   
   Make docToFirst thread-safe and ensure wrap() uses an atomic putIfAbsent 
check so concurrent calls don't race:
   1. Change docToFirst to a ConcurrentHashMap:java
   private final Map<BaseDocument, UndoableEditDelegate> docToFirst = new 
ConcurrentHashMap<>();
   Use code with caution.
   2. Use putIfAbsent in wrap() (to avoid a check-then-act race on 
docToFirst.get(doc)):java
   UndoableEditDelegate current = new UndoableEditDelegate(ed, dob, session);
   docToFirst.putIfAbsent((BaseDocument) doc, current);
   return current;
   Use code with caution.
   3. Keep close() simple (and optionally deactivate first):
   With ConcurrentHashMap, iterating over docToFirst.values() uses a weakly 
consistent iterator that never throws ConcurrentModificationException:java
   public void close() {
       for (UndoableEditDelegate first : docToFirst.values()) {
           first.end();
       }
       docToFirst.clear();
   }
   Use code with caution.
   (If you want an extra guarantee that no straggling background edits get 
added right before docToFirst.clear() without .end() being called, you can also 
iterate over a snapshot or drain the map, or check 
RefactoringSession.reallyDoRefactoring() to ensure setActive(false, null) runs 
before close().)`
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

For further information about the NetBeans mailing lists, visit:
https://cwiki.apache.org/confluence/display/NETBEANS/Mailing+lists

Reply via email to