Question about "mResponseHandler.post(new..."


#1

I have problem to understand the following code:

[code]public class ThumbnailDownloader extends HandlerThread {

private void handleRequest(final Handle handle) {
try {

mResponseHandler.post(new Runnable() {
public void run() {
if (requestMap.get(handle) != url)
return;

                requestMap.remove(handle);
                mListener.onThumbnailDownloaded(handle, bitmap);
            }

[/code]

Is the “new Runable()” run in the UI thread? If so, how can it access the requestMap, url, handle and mListner variables?


#2

The runnable is run on whichever thread mResponseHandler is attached to. In this case, that is indeed the main thread.

Now, about which fields it can access: it can access any instance variables on the enclosing instance, as well as any parameters or variables marked “final”. That visibility is unrelated to the thread the code will eventually run on.

If you want more information on the semantics of how the Runnable class works here, I recommend reading up some more on how anonymous inner classes work.