Tumetsu
Tumetsu

Reputation: 1721

Multiple ports and threading

I am designing Android software where I have to listen n-amount of ports, lets say 10. Every 100ms I want to check out if ports have a new UDP-packet. After receiving packet, the data inside should be passed to the UI-thread.

My question is should I use one thread to receive data from all different ports or should I create own thread for every port, each timed to run at 100ms interval? What is the good practice in these cases?

When port has data, it is deserialized to an object, which is then used to update data in Views in the UI-thread.

I'm quite new with socket-programming and more advanced concurrent-programming so I have been hesitating with this for time without finding any good answers from the web.

Upvotes: 2

Views: 1304

Answers (2)

StuPointerException
StuPointerException

Reputation: 7267

Having a thread per socket seems like overkill and unless the time to de-serialize the object is excessive then you won't see any benefit.

Personally (and like bas pointed out; there's not much in it) I would start out simple and have a single thread checking the 10 ports round-robin and sleeping between the checks. If you start to find that the Thread is taking too much time processing the data and the time between each port being checked is too high then you can add more threads to the pool at that point.

Upvotes: 1

bas
bas

Reputation: 1678

My question is should I use one thread to receive data from all different ports or 
should I create own thread for every port, each timed to run at 100ms interval? 
What is the good practice in these cases?

It does not really matter that much. If you create one thread, you will have to keep track of the different ports. If you create multiple thread you have to keep track of all these threads. Since cpu's are usually multi-threaded nowadays I would go for multiple threads.

As for the 100 ms timer interval, you can create one timer that loops through all threads and collects data from these threads. Make sure you lock it, so that if the timer elapses while the former event is still busy collecting data, these two don't interfere with each other.

Upvotes: 1

Related Questions