1

I'm writing a simple application for an android phone to communicate with a PC over a socket connection.

The phone might write or recieve a message at any time, and the computer might as well. The solution I have used so far works like this:

Create a thread and call READ in it.
Run an infinte loop.
    Check if thread has finished,
        If so grab the READ and process,
        Then start a new thread also calling read.
    Check to see if another object working in another thread wants to write,
        If so grab and write.

Specifically, I am using AsyncTask from the Android API to run the threads.

It all works fine, but I am wondering if creating a new thread for each READ is too performance heavy and/or bad coding, and if so how I can reuse the same thread to have the same behaviour.

Alternatively, is there a better way to handle this situation overall?

Thanks in advance for any advice!

Gray
  • 115,027
  • 24
  • 293
  • 354
yellow
  • 463
  • 1
  • 6
  • 16
  • How many connections to you see as being simultaneous? – Gray Jun 19 '12 at 20:31
  • In this application, there is only ever one client. I just use threads so that READ doesn't block when the application may want to make a WRITE. – yellow Jun 19 '12 at 20:35

2 Answers2

2

Yes, creating a new thread for each read is grossly inefficient for your described need.

Instead, consider creating a single thread, a List<your data type> to hold reads, and a semaphore to flag that data is available. Your thread reads each message, places it into the list, and posts the semaphore to whatever is waiting for data. That 'whatever' then receives whatever is in the list until it empties it, then goes back to waiting on the semaphore.

user207421
  • 305,947
  • 44
  • 307
  • 483
mah
  • 39,056
  • 9
  • 76
  • 93
  • 1
    Just FYI but a better way of sharing data to be read might be to use a `BlockingQueue`. That would combine the `List` and the semaphore. – Gray Jun 19 '12 at 20:41
  • Ahh, I think this is probably the easiest solution to implement. I've already got it all set up and working- I'm just interested in performance. This seems like it would be easy to implement into my current program and solves the issue. – yellow Jun 19 '12 at 20:41
0

You need one read thread and one write thread. Both should use a BlockingQueue to interface with the rest of the application. Although I don't understand why you would have multiple threads wanting to write.

user207421
  • 305,947
  • 44
  • 307
  • 483