I'm working on a Thread that handles all server connections:
public void run() {
//this initializes Socket and PrintWriter/DataInputStream
connect(server, port);
while(true) {
//queue is a BlockingQueue where I put the messages to send
while(!queue.isEmpty()) s
//COMMUNICATE-WITH-SERVER-CODE
}
}
}
The code works, but after a minute or so, my phone starts overheating and battery goes down fast. I know it's because of the infinite loop.
How can I solve it? I want a Thread
which, once started, keeps the connection to the server (so that DataInputStream
and PrintWriter
won't be initialized every time). And I want the thread to be responsive: when I click a Button
it should sent instantaneously a message to the server for processing.
I have implemented a Handler
for communicating Thread->Activity
. But how can I communicate Activity->Thread
?
Any tip would be welcome.
Generally the solution would be to add a polling intervall, ex: sleep the thread for 500ms after each iteration. But in this case there is no need for that, because we do not have to poll a BlockingQueue
. From the doc
A
Queue
that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
If we use a BlockingQueue
, then the queue.pop() call blocks if the queue is empty and remains blocked until an entry is pushed onto the queue. There fore there is no need for looping.
However, we will need to have some sort of mechanism to keep the thread from terminating. Here is a simple example:
public void run() {
try {
while (true) {
handleServerIO(queue.take());
}
}catch (InterruptedException ex) {
... handle ...
}
}