To know more about threads synchronization


Assignment#2 presented you an scenario where multiple threads handle one client each. However, given that each thread has to send a text line to each any other thread's client, a synchronization problem may happen.

If all you use to test server's code is a few telnet clients running on your computer, it is difficult you see any problem (as only one client is typing at a time). If you're interested on researching this topic further, you may use IMTester.java code. This program will throw one hundred simultaneous clients to your server, each one sending on hundred text lines and then the mandatory quit command.

You may well see errors like this "Exception in thread "Thread-85" java.util.ConcurrentModificationException" on the server program. It basically means that an object was modified while others were reading from it (not a good thing). While I was not interested on raising this topic of synchronization, some of you pointed it out, so I cannot avoid explaining a bit more.

The main problem happens because the list of clients may change while one (or more) thread is iterating through it. If the client list changes while messages are being sent to other clients it is possible that either a client is missing the message or that a message is attempted to be delivered to client who is gone.

The solution is pretty simple but not obvious, and most of you failed to provide a proper one (not that it was a requirement though). I'm including an slightly modified version of my sample implementation for you that addresses the synchronization problem. The basic idea is that looping through client list and removing a client from the list are performed exclusively.

Update: A Vector object should have been used instead of ArrayList (as Vector is Thread safe and ArrayList is not).

4 comments:

Anonymous said...

I've just downloaded and tested the modified version and it still suffers from many java.util.ConcurrentModificationExceptions. However, I'm unable to see why ;)

misan said...

What code are you using for the clients?

What JDK version are you using?

misan said...

Oops, I've seen the error and its cause. A Vector object should have been used instead of ArrayList (as Vector is Thread safe and ArrayList is not).

My mistake!

Just do this change and it will be fine.

Anonymous said...

OK, that did the trick. Thanks!