Killing an *unresponsive* thread in Android/Java - android

I know the accepted, correct solutions for gracefully closing a thread.
But assume my game is supposed to be fault-tolerant, and when a new gamegplay is started, it tries to gracefully close the (now-paused) thread of the old gameplay. If it fails to join it / close it (e.g. because the old thread is buggy and is in an infinite loop), it instantiates the new Thread and starts it. But I don't like the fact that the old thread is still there, eating resources.
Is there an accepted way to kill an unresponsive thread without killing the process? It seems to me there isn't, in fact, I read somewhere that a Thread might not react to Thread.stop() either.
So there is no way dealing with a thread in an infinite loop (e.g. due to a bug), is it? Even if it reacts to Thread.stop(), the docs say that Thread.stop() may leave Dalvik VM in an inconsistent state...

If you need this capability, you must design it and implement it. Obviously, if you don't design and implement a graceful way to shut down a thread, then there will be no way to gracefully shut down a thread. There is no generic solution because the solution is application-specific. For example, it depends on what resources the thread might hold and what shared state the thread may hold locks on or have corrupted.
The canonical answer is this: If you need this capability, don't use threads. Use processes.
The core reason is the way threads work. You acquire a lock and then you manipulate shared data. While you're manipulating that shared data, it can enter an inconsistent state. It is the absolute responsibility of a thread to restore the data to a consistent state before releasing the lock. (Consider, for example, deleting an object from a doubly-linked list. You must adjust the forward link or the reverse link first. In between those two operations, the linked-list is in an inconsistent state.)
Say you have this code:
Acquire a lock or enter a synchronized block.
Begin modifying the shared state the lock protects.
Bug
Return the data the lock protects to a consistent state.
Release the lock.
So, now, what do we do? At step 3, the thread holds a lock and it has encountered a bug and triggered an exception. If we don't release the lock it acquired in step 1, every thread that tries to acquire that same lock will wait forever, and we're doomed. If we do release the lock it acquired in step 1, every thread that acquires the lock will then see the inconsistent shared state the thread failed to clean up because it never got to step 4. Either way, we're doomed.
If a thread encounters an exceptional condition the application programmer did not create a sane way to handle, the process is doomed.

Related

What would cause a thread interrupt?

I'm familiar with both what an interrupt is used for (to put it roughly: asking the interrupted thread kindly to terminate or at least stop its work as soon as conveniently possible, instead of killing it immediately) as well as how to handle it properly (in most common cases, maybe not the tricky ones).
But I'm having a hard time to understand who (if not my own code) could even call Thread.interrupt() in the first place, and when this "third party interrupt" could occur.
I'm finding lots of information on why anybody would want to interrupt a thread, but hardly anything about who would do that for "my" threads unless I coded it myself.
So on Android, if my own app code does not contain any calls to Thread.interrupt() or something similar like AsyncTask<,,>.cancel(), will any thread I start ever be interrupted at all?

Starting singleTask activity every few seconds gives ANR in Android

In the app I have an activity which has launch mode as singleTask. There are number of use cases which pass through this activity and hence it's called number of times. On stress testing the app by running monkeyrunner script and calling this activity every few seconds causes ANR's.
I guess, the way it's designed where most of the use cases pass through this activity is not correct but I am not in a position to change this design.
Is there anyway ANR's can be suppressed? I mean, adding UI operations to event queue so that it doesn't block main UI thread and doesn't give ANR.
It is unclear from the question what your activity is (or should be) doing. Probably you need a service instead.
It is common to perform time-consuming operations in background threads and deliver the results to the UI thread.
You may use the classes Handler/Looper (it it easir to send Runnables rather than messages), or use an AsyncTask. The AsyncTask is nevertheless tricky, this is discussed here: Is AsyncTask really conceptually flawed or am I just missing something? . AFAIK Google tried to fix the typical bugs and made the new behavior incompatible with the old one (namely, I have seen some misbehavior on the newer Androids that may be explained by the assumption that since some version threads doing asynctask jobs get killed after the activity that started them goes out of the screen).
I can guess that singleTask is your way to fight the fact that an activity dies when the screen turns, and a new one comes. I suggest you use singletons (they survive screen rotation but do not survive a process restart, one more thing that sometimes happens in Android). (The user switches to an app like Camera, takes a big photo, returns back -- and the activity is restarted because Camera needed memory. Have seen this in practice, but that time I did not try to find out if the whole process was restarted.)
Anyway, please add logging telling you when your activity in entered and left, including onNewIntent() and other lifecycle functions (to be on the safe side, I recommend to print the thread names as well). Then you will probably see what is going on.

When do blocked Android threads actually get killed?

I'm fighting the known bug in Android that a blocked USB read thread cannot be unblocked - period. Nothing unblocks it; not closing the underlying object (as is typical with sockets), not using NIO and calling FileChannel.close (which sends an exception to the blocked thread), nothing. So I'm stuck crafting up some sort of workaround that tolerates this bug in Android.
The biggest problem is that since the thread won't die, it retains a reference to the underlying FileInputStream object (or the FileChannel object, or whatever you're using). Because that object still exists, you cannot reassociate with the connected USB device. You get the well-known "could not open /dev/usb_accessory" message of despair.
So... since the thread cannot be killed nor interrupted externally, and since it won't wake up on its own to release the object, I'm wondering when such a blocked thread and its associate resources are cleaned up by the operating system. In most OS's the thread would be part of the overall process, and when that process is terminated all threads and objects would get cleaned up at the same time - thus finally releasing the USB connection so something else can associate with it. But experiments suggest that the thread or object may live beyond the process. How, and in what context, I don't know, but so far I'm still getting that "could not open /dev/usb_accessory" message even after the previous process has been terminated (!?!).
So... what finally cleans up everything associated with a process, including all of its threads and instanced objects? How do I "clean the slate" so a new process has a fresh shot at associating with /dev/usb_accessory?
Thanks!

Is it ok to perform DB operation on UI thread?

I am using a database to persist the state of a search form. I am using the onPause method to persist the data and the onResume method to restore it. My opinion is that restoring and persisting state should be a blocking operation so I plan to perform the database operations on the UI thread. I know this is generally discouraged but the operations should be quick and I think if they were done asynchronously they could lead to inconsistent UI behaviour.
Any advice
Even if you want the application to not accept user input while the slow operations are being performed, you still don't want to do them in the UI thread. This is for two reasons:
Fully non-responsive UIs are a big nono. If you need to lock your user away from interacting with the program, you need to assure him that something is actually going on - anything else is likely to be interpreted as your application being buggy. Use dialogs, toasts and/or progressbars while the application is working, as appropriate.
Android will offer users the option of force-closing applications that it thinks are hanging. You don't want this to happen during what is normal behaviour for your application is taking place.
Even if you want it to be a blocking operation, you have to show the user that some thing is happening. Because when the UI thread is blocked, the screen will not respond to any touch operation of the user. Sp, you can have an indefinite progress bar in your onPause() and onResume() methods till the persistence and restoration is done. And obviously you will have to do it in a separate thread. Because if the UI thread is not responding for sometime, android can give the Application Not Working error.

Possible states for native threads on Android?

What are all the possible thread states during execution for native (C/C++) threads on an Android device? Are they the same as the Java Thread States? Are they Linux threads? POSIX threads?
Not required, but bonus points for providing examples of what can cause a thread to enter each state.
Edit: As requested, here's the motivation:
I'm designing the interface for a sampling profiler that works with native C/C++ code on Android. The profiler reports will show thread states over time. I need to know what all the states are in order to a) know how many distinct states I will need to possibly visually differentiate, and b) design a color scheme that visually differentiates and groups the desirable states versus the undesirable states.
I've been told that native threads on Android are just lightweight processes. This agrees with what I've found for Linux in general. Quoting this wiki page:
A process (which includes a thread) on a Linux machine can be in any of the following states:
TASK_RUNNING - The process is either executing on a CPU or waiting to be executed.
TASK_INTERRUPTIBLE - The process is suspended (sleeping) until some condition becomes true. Raising a hardware interrupt, releasing a system resource the process is waiting for, or delivering a signal are examples of conditions that might wake up the process (put its state back to TASK_RUNNING). Typically blocking IO calls (disk/network) will result in the task being marked as TASK_INTERRUPTIBLE. As soon as the data it is waiting on is ready to be read an interrupt is raised by the device and the interrupt handler changes the state of the task to TASK_INTERRUPTIBLE. Also processes in idle mode (ie not performing any task) should be in this state.
TASK_UNINTERRUPTIBLE - Like TASK_INTERRUPTIBLE, except that delivering a signal to the sleeping process leaves its state unchanged. This process state is seldom used. It is valuable, however, under certain specific conditions in which a process must wait until a given event occurs without being interrupted. Ideally not too many tasks will be in this state.
For instance, this state may be used when a process opens a device file and the corresponding device driver starts probing for a corresponding hardware device. The device driver must not be interrupted until the probing is complete, or the hardware device could be left in an unpredictable state.
Atomic write operations may require a task to be marked as UNINTERRUPTIBLE
NFS access sometimes results in access processes being marked as UNINTERRUPTIBLE
reads/writes from/to disk can be marked thus for a fraction of a second
I/O following a page fault marks a process UNINTERRUPTIBLE
I/O to the same disk that is being accessed for page faults can result in a process marked as UNINTERRUPTIBLE
Programmers may mark a task as UNINTERRUPTIBLE instead of using INTERRUPTIBLE
TASK_STOPPED - Process execution has been stopped; the process enters this state after receiving a SIGSTOP, SIGTSTP, SIGTTIN, or SIGTTOU signal.
TASK_TRACED - Process execution has been stopped by a debugger.
EXIT_ZOMBIE - Process execution is terminated, but the parent process has not yet issued a wait4() or waitpid() system call. The OS will not clear zombie processes until the parent issues a wait()-like call.
EXIT_DEAD - The final state: the process is being removed by the system because the parent process has just issued a wait4() or waitpid() system call for it. Changing its state from EXIT_ZOMBIE to EXIT_DEAD avoids race conditions due to other threads of execution that execute wait()-like calls on the same process.
Edit: And yet the Dalvik VM Debug Monitor provides different states. From its documentation:
"thread state" must be one of:
1 - running (now executing or ready to do so)
2 - sleeping (in Thread.sleep())
3 - monitor (blocked on a monitor lock)
4 - waiting (in Object.wait())
5 - initializing
6 - starting
7 - native (executing native code)
8 - vmwait (waiting on a VM resource)
"suspended" [a separate flag in the data structure] will be 0 if the thread is running, 1 if not.
If you design a system app that has to work with threads in even more advanced way than usual app, I'd first start by examining what API is available on Android to access threads.
The answer is pthread = POSIX threads, with pthread.h header file, implemented in Bionic C library. So you have starting point for knowing what you can achieve.
Another thing is that Android doesn't implement full pthread interface, only subset needed for Android to run.
More on threads + Bionic here, and how they interact with Java and VM is described here. Also I feel that thread is actually a process, as my code uses setpriority(PRIO_PROCESS, gettid(), pr); to set new thread's priority - I don't recall where I got this info, but this works.
I assume that thread may be in running, finished or blocked (e.g. waiting for mutex) state, but that's my a bit limited knowledge since I never needed other thread state.
Now question is if your app can actually retrieve these states using available API in NDK, and if there're more states, if your users would be really interested to know.
Anyway, you may start by displaying possibly incomplete states of threads, and if your users really care, you'd learn about another states from users' feedback and requests.
Google:
Thread.State BLOCKED The thread is blocked and waiting for a lock.
Thread.State NEW The thread has been created, but has never been started.
Thread.State RUNNABLE The thread may be run.
Thread.State TERMINATED The thread has been terminated.
Thread.State TIMED_WAITING The thread is waiting for a specified amount of time.
Thread.State WAITING The thread is waiting.
These states are not very well explained - I don't see the difference between BLOCKED and WAITING, for example.
Interestingly, there is no 'RUNNING' state - do these devices ever do anything?

Categories

Resources