• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wait and notify not involving inter-thread communication

 
Anton Shaikin
Ranch Hand
Posts: 65
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm writing a simple UDP server to handle multiple client requests simultaneously. To implement that I create a separate thread for each client request. I know that it's not a good decision in the long run, and I did read a little bit about the Reactor pattern and use of NIO in such situations. But I don't want things to get complicated.
So, let me show you the code:

HandlerThread just processes the received packet:

Now after registered client sends another packet I need some way to wake up already created thread, instead of creating a new one (to maintain sort of session).
The main question is how to implement it? I don't want to put a handler thread to sleep for some time, and then check for some condition.
Also, I see no place for standard wait(), notify() methods as there is no inter-thread communication. There is a separate unit of work for each created thread, and there are no shared resources.
 
Andrey Kozhanov
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's possible to use java.util.concurrent mechanism in your case. For example, create singleton class which will contain one Lock instance and multiple Condition instances - one per client thread. Then in your client threads call 'await' method of Condition instance for this thread and in line 7 of your code just identify a proper Condition object and call it's 'signal' method to wake up a client thread.
 
Anton Shaikin
Ranch Hand
Posts: 65
IntelliJ IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Andrey, thanks for your reply! Unfortunately I didn't find concurrent utils very useful in my case. You proposed to use single Lock instance for each thread. That just means that in order for a second thread to process client request, the first one should finish and release the lock. In this case I don't see any benefit from multi-threading. I need the ability to process client requests asynchronously and independently as they arrive. The threads in my case, don't use any common data, so they shouldn't be synchronized.
 
Andrey Kozhanov
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That just means that in order for a second thread to process client request, the first one should finish and release the lock


Not quite. The second thread could start with client request not only when first thread is finished but also when it call Condition's (java.util.concurrent.locks.Condition) 'await' method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!