It would appear that the Java machine fails on certain types of loop that appear to be infinite to its system check but are in fact terminated by code outside the loop’s class. This does not happen often, but it was most noticeably found in my recent TickleService, where finite loops of code ran without trouble but loops that required ANY outside termination failed. For example:
class TickleService extends Service{
...
void execute(){
while(true){
Log.e("Test","Tickle");
wait(1000);
}
}
...
}
The above caused an immediate system ANR crash(CPU usage >99% exception).
However, the following version would run only once and cease further operation without ever crashing:
public class TickleService extends Service{
...
public static boolean amNotAlive = false;
void execute(){
while(true){
Log.e("Test","Tickle");
if(amNotAlive)
break;
wait(1000);
}
}
...
}
The above loop executed once and ceased to loop.
Next, if the code had a finite loop it would execute flawlessly:
public class TickleService extends Service{
...
public static boolean amNotAlive = false;
void execute(){
for(int i = 0; i<5;i++){
Log.e("Test","Tickle");
wait(1000);
}
}
...
}
This above loop would run 5 times each one second apart as expected.
Ultimately, the fix I applied was to run the following in which I tried to trick the JVM into thinking that no looping was occurring at all:
public class TickleService extends Service{
...
public static boolean amAlive = true;
void execute(){
Log.e("Test","Tickle");
wait(1000);
if(amAlive)
restartService(); //pseudo code for doing startService on self
}
...
}
This trick executed without exception and reliably produced tickles one second apart.
Many tests were run, all confirmed that continuous loops failed if they terminated according to triggers outside the class, but ran correctly if terminated internally. Ultimately, while I strongly suspect either a purposeful design flaw or unintended bug in the Dalvik java machine causes this problem, but the evidence was only circumstantial. Furthermore, the problem does not seem to occur for all services that I have written in Android. Does anyone know why this is? I would love to understand this problem better.
The Dalvik Virtual Machine is running correctly in all cases you have shown. Running infinite loops and thus blocking the main UI thread is poor practice and will only get you ANR errors. I haven’t seen your other code so I cannot respond to it.