0

So my program is a version of paint.

It creates a canvas and allows me to paint over the canvas with my mouse by getting Point's from the mouse using a HashSet and Iterator.

It also connects to another identical program via a DatagramSocket and sends the Point's it generates to the other program which displays this on it's canvas.

To do this I use a Runnable thread that listens for incoming Point's and adds them to the HashSet.

My problem is that i get java.util.ConcurrentModificationException because I add Point's to the HashSet from the connected program via the thread while painting.

I don't see how to get around this exception since I want the canvas to update live.


solved this using a CopyOnWriteArraySet with which I could simply replace my HashSet :) thx for all your support!

shurda
  • 67
  • 8
  • In the loop create a new Set and afterwards addAll the set to the original Set. Still concurrency issues arise during adding, so you have to guard that as well. – Joop Eggen Jan 03 '20 at 14:33

2 Answers2

2

Use ConcurrentSkipListSet instead of HashSet. This Set implementation is ordered and thread safe.

As MikeFHay mentions, you can also use another thread safe Set implementation - ConcurrentHashMap.KeySetView. It can be instantiated by using ConcurrentHashMap.newKeySet() method. This Set is faster then ConcurrentSkipListSet and is not ordered.

Niebian
  • 86
  • 7
  • 2
    or `ConcurrentHashMap.newKeySet()`, which also supports concurrent modification, and is generally faster than ConcurrentSkipListSet. – MikeFHay Jan 03 '20 at 14:37
0

You can avoid the situation by locking the set. Use 'synchronized' block in both threads and lock the set before accessing them so no two threads modify the set at the same time.

This might help

Afridi Kayal
  • 2,112
  • 1
  • 5
  • 15
  • Dope, but wouldn't this cause the cause each program to wait for updating the canvas with the points from the connected program until it finishes reading user input? – shurda Jan 03 '20 at 14:31
  • This drawback is mentioned in the link too. Locking an object will halt the update and retrieval at the same. But, if the threads aren't locking the object for a while, this method can be used to avoid the ConcurrentModificationException. Make sure you release the lock if the object is not being modified. Avoid locking the object for a while. – Afridi Kayal Jan 03 '20 at 15:06