Android application Thread CPU GC operatiing and OOM Question 0603-Handy notes

Source: Internet
Author: User

Before the app finishes testing, no problem to complete the entire aging phase including data transceiver, key in adb shell top-m 5 I found my app pid occupied

CPU is the most, in fact I want to say that writing an app is not difficult, you do not have a comprehensive analysis of the memory usage of the app? Avoid problems such as oom, and other

can bring about some of the occasional problems. These are expected to be a lot of small partners did not consider, nothing, today to everyone to talk about this aspect of things. It's not a difficult thing, though.

knowledge points, but the most important thing is to develop this kind of habit, ability to reduce unnecessary waste of time in the development of a might. I'll show you how to find and solve the problem .

Problem. Step-by-step analysis


First look at the CPU usage of our app:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvannwcgluzw==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">

We can see the com.digissin.twelve this process is always ranked first, this is our test process, the following I take small friends how to find out to ask

and correct them in a timely manner.


First we have to analyze. Why is CPU usage so high? is not a time-consuming operation on the main thread or the child thread. Network operation, too many instance objects for new?

With this question. Let's look at the DDMS and analyze:



View Com.digissin.twelve.rsudpprotocol&postbytesthread 134 lines of code:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvannwcgluzw==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">


The dead loop reads the state, but cannot remove the dead loop, because the app needs this dead loop to communicate to the server, only if it is not an accident, the app is

Keep communication with the backstage! When there is data coming in, Ispause will be set to true, and the code flow will go to if, once a datagram is sent out.

Ispause false While it is used to enter the empty dead loop. No matter what, and the frequency of very fast cycle operation. Suppose we call sleep () in this dead loop

Despite being successful. But obviously it runs counter to the needs of the app. So it must be ruled out, because once entered the sleep () thread will not work, from the main line into the

The datagram sent by the agreement is no matter what it means! So this is not the way to take it.


So I quickly think of a way, that is, when ispause false, we do not need to work on sub-threads. That's very easy, I just need to let him sleep, once

There are datagrams sent from the agreement. We just wakeup to let the child threads continue to work. Then non-wait () and notify () are the first to differentiate between Thread and

Object of these two things inside of Wait () and notify (), source code analysis is too general, I give you examples of analysis

Calling these 22 functions directly in thread is not going to work, and we need to create an object to manage the pauses and continuation of the child threads, which means

A child thread is equivalent to an ordinary employee. A new Object object is the equivalent of a manager, what the employee needs to do to inform and inform the manager, even if the member

Workers know what they want to do next, they need the approval of the manager!

Employees are also unable to separate themselves. Just can't do their own thing,

Otherwise the entire management mode will be messed up, so we have to create an object to do this pause and continue control on the child thread.


So I give this inner class line loads synchronized field. And adding an instantiated static method to create this object (Postbytesthread) instance

and give the pause and resume functions:

        private static Postbytesthread mthreadinstance = null;              Public synchronized static Postbytesthread Getthreadinstance () {if (mthreadinstance = = null) {              Mthreadinstance = new Postbytesthread ();          } return mthreadinstance; } public synchronized Boolean ispause () {return ispause;} Public synchronized void Setpause (Boolean ispause) {this.ispause = Ispause;} Public byte[] Getpost_bytes () {return post_bytes;} public void Setpost_bytes (byte[] post_bytes) {this.post_bytes = post_bytes;} Public synchronized void Onthreadpause () {try {log.e (TAG, tag+ "onthreadpause ()----"); this.wait ();} catch ( Interruptedexception e) {log.i (TAG, e.tostring ());}}    Public synchronized void Onthreadresume () {LOG.E (TAG, tag+ "onthreadresume ()----"); this.notify ();            @Override public void Run () {if (Udpsocket = = null) {LOG.I (TAG, tag+ "Udpsocket is null");            Return   } while (true) {     LOG.I (TAG, tag+ "Ispause () state:" +ispause ());        if (Ispause ()) {try {sendpacket.setdata (getpost_bytes ());        Sendpacket.setlength (Getpost_bytes (). length);        Sendpacket.setaddress (serveraddress);        Sendpacket.setport (DEFAULT_POTR);        Udpsocket.send (Sendpacket);        Thread.Sleep (1000);        Setpause (FALSE);        } catch (Interruptedexception e) {log.i (TAG, "Exception:" +e.tostring ());        } catch (IOException e) {log.i (TAG, "Exception:" +e.tostring ());        }}else{Onthreadpause (); }}    }    }

The callback interface receives the protocol message packet distribution from the main thread, and starts working, of course, just for the convenience of everyone to watch, in fact the start () method does not have to be sent here, because this synchronization object only in the child thread extinction will be recycled, So it's the equivalent of inferring one instance of this synchronization object at a time.

    public void Setpostbytesdata (byte[] data) {    postbytesthread.getthreadinstance (). Start ();    Postbytesthread.getthreadinstance (). Onthreadresume ();    Postbytesthread.getthreadinstance (). Setpause (true);    Postbytesthread.getthreadinstance (). setpost_bytes (data);    Boolean ispause = Postbytesthread.getthreadinstance (). Ispause ();    LOG.D ("Postbytesthread", "Postbytesthread  Ispause () state:" +ispause);    }

After processing this code we continue to look at CPU usage:


You can see that the CPU usage of com.digissin.twelve is greatly reduced. So as to achieve our goal. At the same time of solving the problem, I also tell you a

Often made mistakes, and in the form of code and gaze to see clearly

To create an unnecessary new instance:

In the case of some progress bar updating or uploading data, we usually need to keep the UI new and so on, which involves the interaction of the child thread with handler. Need

We can make this mistake by constantly sending a message object to handler. For example, the following:

@Overridepublic void Run () {while (true) {try {settinglocationtime ()} catch (Interruptedexception e) {E.printstacktrace ();}}} private void Settinglocationtime () throws Interruptedexception{if (Handler!=null) {SendMessage (post_data); time = SETTING_TIME>0?SETTING_TIME:DEFAULT_TIME;//LOG.I (TAG, tag+ "Settinglocationtime () Time:" +time); Thread.Sleep (time*1000);}} /** * This function will run in run while (true) * Message\bundle will be constantly creating new instance objects * So this is a very low error! It's deadly, too! * */private void SendMessage (byte[]data) {Byte[]_data=byteparsebeantools.postprotocolbyte ( Byteprotocolsessiontype.location_state_send, data); Message msg = new Message ();  Unnecessary Message new instance object Msg.what=mainsessionutil.send_post_byets_data; Bundle bundle = new bundle (); Unnecessary bundle new Instance Object Bundle.putbytearray (Mainsessionutil.bytes_data_key, _data); Msg.setdata (bundle); Handler.sendmessage (msg);}

How to resolve:

@Overridepublic void Run () {while (true) {try {settinglocationtime ()} catch (Interruptedexception e) {E.printstacktrace ();}}} private void Settinglocationtime () throws Interruptedexception{if (Handler!=null) {SendMessage (post_data); time = SETTING_TIME>0?SETTING_TIME:DEFAULT_TIME;//LOG.I (TAG, tag+ "Settinglocationtime () Time:" +time); Thread.Sleep (time*1000);}} /** * can put bundles in the place where class is loaded. Instantiate this object * Once the data is loaded, running the clear () function before the next call is possible. The bundle object at this time is equivalent to an Iron bowl * each time a different water, it avoids every time to open up a new memory space to store the bundle object * Message object is more simple, because I this kind of callback a handler object come over, we can directly * Call the Obtainmessage () function of the handler object, which is the function when handler is created. Whether you use it or not. It's all there * die with handler, no need to instantiate. No need to create, can be directly removed to use. This avoids having to open a new memory space * To load the message object, Obtainmessage () function from Messagepool * **/private void SendMessage (byte[]data) {bundle.clear ();//Pour out the old water in the bowl (empty the previous cache), and install the new water (fill in the new data from the callback function) Byte[]_data=byteparsebeantools.postprotocolbyte ( Byteprotocolsessiontype.location_state_send, data);  Message msg = Handler.obtainmessage (); From Messagepoolmsg.what=mainsessionutil.send_post_byets_data;bunDle.putbytearray (Mainsessionutil.bytes_data_key, _data);//Install new water (fill new data source) Msg.setdata (bundle); Handler.sendmessage ( msg);}

This can reduce the CPU consumption problem, and the problem can be solved.


Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

Android application Thread CPU GC operatiing and OOM Question 0603-Handy notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.