I have a Runnable (say "MyThread") that executes a long task and also uses/locks a Thread-Safe Singleton.
I have noticed that when the back button is pressed the screen immediately exits the activity and there is no visual indication that the MyThread has properly finished.
This is evidenced also by the fact that when I 'reopen' my app the singleton is still locked!!!! and of course getLockedInstance() returns null.
So I guess my question is.... what exactly happens to android applications when the back button is pressed even when it is executing critical tasks? Are the threads terminated? Are the threads of the activity frozen and therefore all data being accessed and used? How do we ensure critical tasks are allowed to finish executing?
// singleton class
public class Storage
{
private int count = 0;
private static final Storage ourInstance = new Storage();
public static synchronized Storage getLockedInstance()
{
if (ourInstance.count > 0)
return null;
ourInstance.count++;
return ourInstance;
}
public synchronized void UnlockInstance()
{
if (count > 0)
count--;
}
}
// runnable declaration
private Runnable MyThread = new Runnable()
{
@Override
public void run()
{
Storage s = Storage.getLockedInstance();
..... do stuff .....
[back button pressed]
..... this is never reached .....
s.UnlockInstance();
}
}