Scorpius 144 Posted January 8, 2018 Here's a snippet demonstrating how I worked around the ConcurrentModificationException that gets thrown due to multi-threaded scripts attempting to add/remove something to the same list at the same time causing the entire script to freeze. This should work with any other data type that produces the same behaviour // Our dummy hot list that throws ConcurrentModificationException when we try to add/remove something to/from it List<String> myHotList = new ArrayList<String>(); // Assume this gets called wherever public not-so-static void zFunction() { int attempts = AddToList(myHotList, "zHotString"); System.out.println("Added new hot string in " + attempts + " attempts"); attempts = RemoveFromList(myHotList, "zHotString"); System.out.println("Removed old but still hot string in " + attempts + " attempts"); } // Our magic functions private int AddToList(List<String> zList, String new_string) { int attempts = 0; while(true) { try { attempts++; zList.add(new_string); break; } catch(Exception | Error e) { } try { Thread.sleep(3333); } catch(Exception | Error e) { } } return attempts; } private int RemoveFromList(List<String> zList, String old_but_hot_string) { int attempts = 0; while(true) { try { attempts++; zList.remove(old_but_hot_string); break; } catch(Exception | Error e) { } try { Thread.sleep(3333); } catch(Exception | Error e) { } } return attempts; }
GetBig 1 Posted January 9, 2018 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.htmlThere, problem solved
GetBig 1 Posted January 9, 2018 how did u pass a scripting test if u think this is how concurrency should be handled, not even trying 2 be mean
Scorpius 144 Author Posted January 9, 2018 https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CopyOnWriteArrayList.html There, problem solved Are there other similar classes for other data types?
hexagon 18 Posted January 9, 2018 https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
Scorpius 144 Author Posted January 9, 2018 https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html Cheers!
Recommended Posts
Archived
This topic is now archived and is closed to further replies.