Document directory
- Nobody wants to be slow
- Watching strictmode
- Tips on being smooth
- Our experience
- The future
From: http://feedproxy.google.com /~ R/Blogspot/hsdu /~ 3/auyfpwoj5tu/new-gingerbread-api-strictmode.html
Back Story
One great thing about Google is "20% Time": spending 20% of your time working on projects outside your main focus area. when I joined Google, I bounced all over the place, often joking that I had seven 20% projects. one project I kept coming back to was android. I loved its open nature, giving me access to do whatever I wanted, including opening my garage door when I approached my house on my motorcycle. I really wanted it to succeed but I worried about one thing: It wasn' t always super smooth. animations wowould sometimes stutter and UI elements weren't always immediately responsive to input. it was pretty obvious that things were sometimes happening on the wrong thread.
As a heavy SMS user, one of my 20% projects during the cupcake (Android 1.5) release was speeding up the messaging app and making it feel smoother. I got the app to a happy state and then continued bouncing between other 20% projects. when the donut (Android 1.6) release came out, I noticed that a few of my messaging optimizations had been accidentally broken. I was sad for a bit but then I realized what Android really needed was always-on, built-in, pervasive performance monitoring.
I joined the android team full-time just over a year ago and spent a lot of time investigating froyo performance issues, in particle debugging anrs (those annoying dialogs you get when an application stallits main thread's loalls ). debugging anrs with the tools at hand was painful and boring. there wasn't enough instrumentation to find the causes, especially when multiple processes were involved (doing binder or contentresolver operations to services or contentproviders in other processes ). there had to be a better way to track down latency hiccups and anrs...
Enter strictmode
"I see you were doing 120 MS in a 16 MS zone ..."
Strictmode is a new API in gingerbread which primarily lets you set a policy on a thread declaring what you're not allowed to do on that thread, and what the penalty is if you violate the policy. implementation-wise, this policy is simply a thread-local integer bitmask.
By default everything is allowed and it won't get in your way unless you want it to. The flags you can enable in the thread policy include:
Detect disk writes
Detect disk reads
Detect network usage
On a violation: Log
On a violation: Crash
On a violation: Dropbox
On a violation: show an annoying Dialog
In addition, strictmode has about a dozen hooks around most of the places that hit the disk (in Java. io. *, android. database. SQLite. *, etc) and network (java.net. *) which check the current thread's policy, reacting as you 've asked.
Strictmode's powerful part is that the per-thread policies ies are propagated whenever binder ipc cils are made to other services or providers, and stack traces are stitched together own SS any number of processes.
Nobody wants to be slow
You might know all the places where your app does disk I/O, but do you know all the places where the system services and providers do? I don't. i'm learning, but it's a lot of code. we're re continually working to clarify performance implications in the SDK docs, but I usually rely on strictmode to help catch CILS that inadvertently hit the disk.
Background on disks on phones
Wait, what's wrong with hitting the disk? Android devices are all running flash memory, right? That's like a super-fast SSD with no moving parts? I shouldn't have to care? Unfortunately, you do.
You can't depend on the flash components or filesystems used in most Android devices to be consistently fast. the yaffs filesystem used on your Android devices, for instance, has a global lock around all its operations. only one disk operation can be in-flight when SS the entire device. even a simple "Stat" operation can take quite a while if you are unlucky. other devices with more traditional block device-based filesystems still occasionally suffer when the Block Rotation Layer decides to garbage collect and do some slow Internal flash erase operations. (for some good geeky background reading, see lwn.net/articles/353411)
The take-away is that the "disk" (or filesystem) on mobile devices is usually fast, but the 90th percentile latencies are often quite poor. also, most filesystems slow down quite a bit as they get more full. (See slides from Google I/O Zippy Android apps talk, linked off code.google.com/p/zippy-android)
The "main" thread
Android callbacks and lifecycle events all typically happen on the main thread (aka "UI thread "). this makes life easier most of the time, but it's also something you need to be careful of because all animations, scrolls, and flings process their animations by callbacks on the main thread.
If you want to run an animation at 60 FPS and an input event comes in (also on the main thread), you have 16 MS to run your code reacting to that input event. if you take longer than 16 MS, perhaps by writing to disk, you 've now stuttered your animation. disk reads are often better, but they can also take longer than 16 MS, especially on yaffs if you're waiting for the filesystem lock that's held by a process in the middle of a write.
The network is especially slow and inconsistent, So you shoshould never do network requests on your main thread. in fact, in the upcoming honeycomb release we 've made network requests on the main thread a fatal error, unless your app is targeting an API version before honeycomb. so if you want to get ready for the honeycomb SDK, make sure you're never doing network requests on your UI thread. (See "tips on being smooth" below .)
Enabling strictmode
The recommended way to use strictmode is to turn it on during development, learn from it, and turn it off before you ship your app.
For example, in your application or component's oncreate ():
Public void oncreate () {<br/> If (cmd_mode) {<br/> strictmode. setthreadpolicy (New strictmode. threadpolicy. builder () <br/>. detectdiskreads () <br/>. detectdiskwrites () <br/>. detectnetwork () <br/>. penaltylog () <br/>. build (); <br/>}< br/> super. oncreate (); <br/>}
Or, simply:
Public void oncreate () {<br/> If (cmd_mode) {<br/> strictmode. enabledefaults (); <br/>}< br/> super. oncreate (); <br/>}
That latter form was specifically added so you can target pre-Gingerbread API versions but still easily enable strictmode using reflection or other techniques. for instance, you cocould be targeting donut (Android 1.6) but still use strictmode if you're testing on a gingerbread device or emulator, as long as you use enough reflection to call strictmode. enabledefaults ().
Watching strictmode
If you're using penaltylog (), the default, just run ADB logcat and watch the terminal output. Any violations will be logged to your console, slightly rate-limited for duplicate elimination.
If you want to get fancier, turn on penaltydropbox () and they'll be written to the dropboxmanager, where you can extract them later
# ADB shell dumpsys Dropbox data_app_strictmode -- print
Tips on being smooth
In addition to thread and Java. util. Concurrent. *, check out some of the android APIs such as handler, asynctask, asyncqueryhandler, and intentservice.
Our experience
During Android development we have a new "dogfood" build each day that the whole team uses. throughout the development of gingerbread we set up our daily dogfood builds to enable strictmode logging and upload all found violations for analysis. every hour a mapreduce job runs and produces an interactive report of all the event loop stils, their stack traces (including cross-process ones), their latency percentiles, which processes/packages they appear in, etc.
Using the data from strictmode we fixed hundreds of responsiveness bugs and animation glitches all rights ss the board. we made performance optimizations In the android core (e.g. system services and providers) So all apps on the system will benefit, as well as fixing up tons of APP-specific issues (in both aosp apps and Google Apps ). even if you're using froyo today, the recent updates to Gmail, Google Maps, and YouTube all benefited from strictmode data collection gathered on gingerbread devices.
Where we couldn't automatically speed up the system, we instead added APIs to make certain patterns easier to do efficiently. for example, there is a new method sharedpreferences. editor. apply (), which you shoshould be using instead of COMMIT () If you don't need commit ()'s return value. (It turns out almost nobody ever checks it .) you can even use reflection to conditionally use apply (). commit () depending on the user's platform version.
Googlers who switched from froyo to gingerbread without seeing all the baby steps between were shocked at how much more responsive the system became. our friends on the chrome team then recently added something similar. of course, strictmode can't take all the credit. the new concurrent Garbage Collector in gingerbread also greatly CES latency hiccups.
The future
The strictmode API and its capabilities will continue to expand. We have some good stuff lined up for strictmode in Honeycomb but let us know what else you 'd like to see! I'll be answering questions on stackoverflow.com for questions tagged "strictmode". Thanks!