Thread-safe sharing of a List between multiple clients
I am trying to find out what would be the best approach to the following problem:
I have a TCP Server handling multiple clients. They constantly hit the server (send and receive messages).
In the current implementation each client is in its own thread. Within that thread each client checks with database for new messages.
Instead of each thread calling Oracle on its own I would like to create a special thread holding a list of messages, so all of the connected clients could check that list instead.
The issue is that once I will modify the thread (remove from it) then it is no longer thread-safe.
After googling a little bit I found I will need to lock all of threads and then do the necessary modifications to the list. Is that the best solution? It looks like introducing a delay to the server performance.
Thanks for your help!
Re: Thread-safe sharing of a List between multiple clients
Then you should do your best to optimize the code that modifies the list. You're worried about performance but locking the operations on the list is far more important. Without that synchronization, you risk threads reading invalid data because another thread is smack in the middle of making changes to it. This could prove far more disastrous than any performance issues.