• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Need the most simplified version of this

 
Ranch Hand
Posts: 155
1
Eclipse IDE VI Editor Objective C C++ Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I want to concurrently add and remove elements to a TreeSet

I don't want to use any anonymous class, lambda expressions, and all complicated stuff..
 
Sheriff
Posts: 28370
99
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The API documentation tells you how to create a synchronized version of a TreeSet. It's not complicated, check it out.
 
Bartender
Posts: 322
12
IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Paul Clapham wrote:The API documentation tells you how to create a synchronized version of a TreeSet. It's not complicated, check it out.



I'm not sure he was asking about that, although he may need to do that too. I guessed that he saw a ConcurrentModificationException and needs to get around that. Which is coincidentally also explained just below the thread safety solution in the API docs (which are always a good place to start when solving a problem): https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html

Look into how to use a Java Iterator, which has a remove method you can call while going through the list, those are pretty simple to use.
 
Lou Hamers
Bartender
Posts: 322
12
IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As I was refreshing my own memory on Iterators, which apparently has gotten dusty, it occurred to me that maybe even that's not needed if you really just want to add and remove some objects known ahead of time. You could do all the add operations, and then all the remove operations afterwards (in the same method).

But I suspect you'll probably still want to use Iterator's remove(), which allows you to examine each item to determine if it should be removed. You could also create a "remove later list" and avoid using an Iterator entirely, but an Iterator is usually easier.
 
Marshal
Posts: 4698
588
VSCode Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Swapnil Mishra wrote:I want to concurrently add and remove elements to a TreeSet..


Are you modifying the collection concurrently using multiple threads, or trying to make changes while iterating through the elements?
 
Swapnil Mishra
Ranch Hand
Posts: 155
1
Eclipse IDE VI Editor Objective C C++ Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Synchronized Block Approach, any other simple approach??
 
Bartender
Posts: 10983
87
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Explanation:
  • Synchronized Wrapper: The Collections.synchronizedSortedSet ensures thread-safety for modifications like add and remove.
  • External Synchronization for Iteration: Since SortedSet's iterator is not inherently synchronized, external synchronization (synchronized (sortedSet)) is required during iteration.
  • Concurrency: Threads modify the sortedSet concurrently, demonstrating safe access.


  • [Edit:] I ran this a bunch of times and several times it failed to remove Banana.
     
    Lou Hamers
    Bartender
    Posts: 322
    12
    IntelliJ IDE Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Oh, Paul's guess was more correct.

    Well, you also have the option of using synchronized on a method instead of using a block.
    https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

    But be careful, you may still end up with issues if you only synchronize for a short period inside a loop like that, since you have dedicated threads for add/remove. If one thread adds or removes something on that same set object while the other thread is in the process of looping through the set, that would still seem to be a problem requiring some re-design. What if your remove thread is about to work on the last item, but then the add thread adds another item to the end of the Set? The remove thread wouldn't process the last thing just added and that behavior would be fairly random (but maybe that is okay). A thread could skip over things, or process them twice.

    Seeing your simulated processing delay placeholder maybe a different approach would be better, but we'd need context to give useful feedback. The potential maximum size of the set would be a factor too.
     
    Lou Hamers
    Bartender
    Posts: 322
    12
    IntelliJ IDE Linux
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Looks like Carey beat me to a response, but that's showing the kind of thing I had in mind about a different approach.
     
    Carey Brown
    Bartender
    Posts: 10983
    87
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    What would happen if an add or remove were tried during the synchronized loop for printing?

    If an add or remove operation is attempted while the synchronized block is iterating over the SortedSet, it will cause a ConcurrentModificationException. This happens because the TreeSet's iterator is fail-fast—it detects concurrent modifications and throws the exception.

    Here’s why:

       Synchronized Wrapper: The synchronized wrapper ensures that operations like add and remove are thread-safe, but it does not prevent modifications during iteration unless the programmer explicitly synchronizes externally during iteration.

       Fail-Fast Iterator: The iterator from the TreeSet detects structural changes in the set (e.g., additions or removals) during iteration. Even though the SortedSet is synchronized, structural changes by other threads will trigger this exception.

    Here’s an example scenario:

    Fixing the Issue

    To prevent this problem:

       Avoid Modifications During Iteration: Ensure that add or remove operations are not performed during iteration.
       Copy Before Iteration: Use a snapshot copy of the set for iteration:

    Alternate Data Structures: Consider using a concurrent collection like ConcurrentSkipListSet if high-concurrency support is required without manual synchronization. However, this doesn't guarantee iteration safety if the set is modified concurrently.
     
    Carey Brown
    Bartender
    Posts: 10983
    87
    Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Would this be better because synchronize lock would be held for a shorter period?

    Yes, your suggested approach is better because it reduces the time the synchronized lock is held, improving concurrency. Here's why:
    Advantages:

       Shorter Lock Duration: The synchronized block is used only to create a copy of the SortedSet. Once the copy is made, the lock on sortedSet is released, allowing other threads to perform operations on the original set.
       No Concurrent Modification During Iteration: By iterating over the copy (copyTreeSet), any concurrent modifications to the original sortedSet during iteration won't affect the loop or cause a ConcurrentModificationException.

    Why This Is Better:

       Reduced Contention: Threads modifying sortedSet are blocked for a shorter period (just enough to copy the elements).
       Thread Safety Maintained: Synchronization ensures a consistent snapshot of the sortedSet at the time of copying.
       Safe Iteration: Iterating over copyTreeSet avoids ConcurrentModificationException.

    Considerations:

       Memory Overhead: There’s a small overhead of creating a TreeSet copy, which might be significant if the set is very large.
       Snapshot Consistency: The iteration represents a snapshot of the sortedSet at the moment of copying. Changes made to the original sortedSet after the copy won't be reflected in the iteration.

    This pattern is a good compromise between safety and performance. If modifications to the SortedSet during iteration are frequent and need to be visible, consider alternatives like ConcurrentSkipListSet.
     
    Life just hasn't been the same since the volcano erupted and now the air is full of tiny ads.
    Smokeless wood heat with a rocket mass heater
    https://woodheat.net
    reply
      Bookmark Topic Watch Topic
    • New Topic