Android. Too much CPU usage - java

I've just developed an app for Android, it is a game but i'm not using 3D graphics. It's a board game where i move ImageViews around on the screen. Since now I haven't yet tested it on a mobile device, just on the emulator. The problem is that when i run my app on a Samsung Galaxy S2 phone (dual ore :( ), the CPU Usage goes up to 85% and the damn phone heats up :D when i kill the process (close the app entirely, so it doesn't run in the background) it goes down to 0 :)
I don't even know where to start fixing the problem. Could you guys give me an idea?
I can only think of two reasons for which this might happen, but they might be stupid reasons:
With the exception of the UI thread, I have 2 more threads, each having an infinite while loop which cycles indefinite and looks if there are any messages in the message queue of each thread. Could this be the case? Should i put a delay in these loops of a couple of milliseconds, so they don't run so fast?
I'm also using around 20-25 imageViews on the screen which i'm moving around with via touch. Could those have anything to do with this?
Is there a way to check for memory leaks or SOMETHING ... from the emulator?
If anyone can offer some advice on how i should approach this issue, i'd be grateful.

"I have 2 more threads, each having an infinite while loop which
cycles indefinite and looks if there are any messages in the message
queue of each thread"
The above thing sounds suspicious to me. Instead of using infinite loop in your own thread, you should really make use of Handler which is designed exactly for this purpose.
As from developer's site:
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each Handler instance is
associated with a single thread and that thread's message queue.
There are two main uses for a Handler:
to schedule messages and runnables to be executed as some point in
the future
to enqueue an action to be performed on a different thread than your
own
Besides, DDMS tab in Eclipse would give you all the required tools to investigate the excess use of CPU.

Related

Android Studio Java Threads

I read about threads in Android Studio and I wanted to ask some questions. Are threads a must have in my application to avoid lag or only when you make really big and consuming apps? I am asking this because I have little lag on my app and I wanted to know if it is because I didn't use threads. I don't think it is because of useless stuff I did, I was pretty vigilant with that.
Threads are a vital component of building any large scale application. For example lets say you have a line of code that performs some unit of work which requires some time to be finished for example
...
// takes 500ms to complete could be a network operation/could be accessing camera,
// initializing recorder etc. (Initalizing recorder takes 100ms most of the time)
doSomeTimeIntensiveTask();
...
In such cases you would need to perform this task on a different thread and not on your UI/MAIN thread because for a end user using the application, IF you were to perform this on the UI/MAIN thread then he/she would notice the time delay as a stutter/lag kind of experience which makes for a bad UI experience in general.
Additionally there are tasks like making a HTTP request that require an in-determinate amount of time to actually finish in such cases, if such tasks was performed on the UI/MAIN thread then the application would be STUCK until the task was completed which sometimes causes the android OS to show pop up messages like the application doesn't seem to be responding do you want to force close the app? or some similar message, which again is bad user experience.
So in your case, I would try to identify exactly which piece of code is causing the lag in my UI/MAIN thread and put that part of the code in a separate thread and write a callback to continue executing correctly.
Without more information, it is impossible for anyone to answer this question in any reasonable manner.
Generally speaking, though, the main reasons to create additional threads (beyond the ones already used in the framework), is if you are doing heavy operations such as I/O (heavy read/write or http), graphics, or really complex calculations.
Look into Processes and Threads and AsyncTask.
To briefly quote the most relevant portion to this question:
When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.

Should I implement the consumer/producer pattern in my java video app, and if yes, how?

I built a small video frame analysis app with desktop Java 8. On each frame, I extract data (5 doubles now, but could expand to a 1920x1080x3 OpenCV Mat in the future). I would like to store this data into a database (Java DB, for example) to perform some time-series analysis, and periodically return the results to the user.
I am worried about hard-drive access times if I write to the database and run the app on a single thread, and the best solution that occured to me would be to implement the producer/consumer pattern with multithreading. The examples I found all implement 3 threads:
the main thread
the producer thread
the consumer thread
Is there an advantage in doing that compared to a 2 thread implementation?
main and producer thread
consumer thread
And is that the right way to handle real-time data with a database?
It's limiting to use a fixed number of threads. My PC has (only) 8 cores, your intensive sounding app is not going to use half of them, indeed probably only the consumer is the intensive one, so maybe 12.5%. You'll have to have several of each thread to get the most out of the CPU, and then you'll spend a lot of effort managing threads.
The alternative is to use one of various existing systems for executing work in the background. For example ThreadPoolExecutor With that you can just throw lots of work at it (Runnables) and it will queue work up, and execution can be scaled to suit the hardware it's running on by customizing the number of worker threads.
Or if you're using Swing, then SwingWorker. The advantage of this is you can do some work on a background thread and post the results on the foreground (main/UI) thread easily.
Your question is rather conceptional, so I think it belongs here: Programmers
But as one short hint from my experience, you separate the producer from the main because your main control may freeze if something goes wrong with the producer. Things like frozen forms, not responding controls etc. may be the result. Give your system a chance to reestablish by command.

Ensuring that threads get (approximately) equal CPU time in Java

I'm writing a game in which players write AI agents that compete against one another, on the JVM. Right now the architecture looks like this:
A core server module that handles the physics simulations, and takes messages from the players as input to alter the world. The core also determines what the world looks like from the perspective of each of the players, based on various rules (think fog of war).
Player modules receive updated versions of the world from the core, process them, and stream messages to the core as inputs based on that processing.
The idea is that the core is compiled along with two player modules, and then the simulation is run producing an output stream that can be played back to generate visualization of the match.
My question is, if each of the players runs on a single Java thread, is it possible to ensure that the two player threads get equal amounts of resources (CPU time, primarily, I think)? Because I don't control the nature of the processing that each AI is doing, it's possible that one of the players might be extremely inefficient but written in such a way that its thread consumes so many resources the other player's AI is resource starved and can't compete fairly.
I get the feeling that this isn't possible without a hard realtime OS, which the JVM isn't even close to being, but if there's even a way to get reasonably close I'd love to explore it.
"Player modules receive updated versions of the world from the core, process them, and stream messages to the
core as inputs based on that processing". This means that player module has a loop inside it which receives update message and sends result messages to the core. Then I would use lightweight actor model, each player being an actor, and all actors use the same ExecutorService. Since activated actors go through the same executor task queue, they got roughly the same access to CPU.
Your intuition is right that this isn't really possible in Java. Even if you had a real-time OS, someone could still write a very resource intensive AI thread.
There are a couple of approaches you could take to at least help here. First be sure to give the two player module threads the same priority. If you are running on a machine that has more than 2 processors, and you set each of the player module threads to have the highest priority, then theoretically they should both run whenever they have something to do. But if there's nothing to stop the player modules from spawning new threads themselves, then you can't guarantee a player won't do that.
So short answer is no, you can't make these guarantees in java.
Depending on how your simulation works, maybe you can have a concept of "turns". So the simulation instructs player 1 to make a move, then player 2 makes its move, and back and forth ,so they can each only make one "move" at a time. Not sure if this will work in your situation though.
If you have any knobs to turn regarding how much work the threads have to do (or just set their priority), you can set up another thread that periodically monitors threads using ThreadMXBeans and find their CPU usage using ThreadInfo.getThreadCpuTime. You can then compare each players CPU time and react accordingly.
Not sure if this is timely and accurate enough for you, but over time you could balance the CPU usage.
However, splitting the work in packets and using Executors like suggested before should be the better way and more java-like.

What type of thread method should I use for continuous work?

My application is currently using ordinary threads to produce servers, clients and even a thread which swaps WiFi networks and starts the previous. Those threads run in the background and dont have any impact on the UI so it is something I was looking for, but the problem is that when I reenter the application all those threads are recreated. Is it possible to create a singleton thread which will be possible to control when we reopen the application?
Android offers some classes also:
Service: but it uses the UI thread...
AsyncTask: probably a better candidate
IntentService: has a worker thread which could be manipulated? Probably best option from above.
Any thoughts/opinions will be highly appreciated. :)
EDIT:
Also why I would want to change my ordinary threads into some other method is because Android will prioritize ordinary threads to get killed.
Thread call hierarchy:
MainActivity -> NetworkSwap(infinite process which is scanning, connecting and swaping WiFi networks), ServerTCP(infinitely listening for connections) , ServerUDP(infininetely listening for connections)
Networkswap -> ClientUDP (sends broadcast request to serverUDP and ends)
ServerUDP -> ClientTCP (sends request to serverTCP and ends)
It's still not entirely clear to me what you're using these threads for. From the title it seems you're doing ongoing work, but in the description it sounds like sometimes you do smaller discrete chunks of work. It's also not clear whether these types of work are related.
That said, with ongoing work I'd say to move your currently existing thread to be managed by a regular Service, thus giving a lifetime that is independent of activities and can do ongoing background work. For smaller discrete chunks of work, IntentService is a better match. If you have these two types of work and they're not very related, you could even consider having both types of services (it sounds like you have multiple threads as is anyway).

Multithreading, Multiprocessing with STOP and Continue Signals

I am working on a project where I need to get the native stack of the Java application. I am able to achieve this partially thanks to ptrace, multiprocessing, and signals.
On Linux, a normal Java application has, at a minimum, 14 threads. Out of these 14, I am interested in only the main thread of which I have to get the native stack. Considering this objective, I have started a separate process using fork() which is monitoring the native stack of the main thread. In short, I have 2 separate processes: one is being monitored and the other does the monitoring using ptrace and signal handling.
Steps in the monitoring process:
Get the main thread ID out of the 14 threads from the monitored process.
ptrace_attach on the main ID.
ptrace_cont on the main ID.
continuous loop starts
{
kill(main_ID, SIGSTOP)
nanosleep and check the status from the /proc/[pid]/stat directory.
ptrace_peekdata to read the stack and navigate.
ptrace_cont on the main ID.
nanosleep and check the status from the /proc/[pid]/stat directory.
}
ptrace_detach on the main ID.
This perfectly gives the native stack information continuously. However, sometimes I encounter an issue:
When I kill(main_ID, SIGSTOP) the main thread, the other threads from the process get into a finished or stoped state (T) and the entire process blocks. This is not the consistent behavior and sometimes entire process executes correctly. I cannot understand this behavior as i am only signaling the main thread. Why are the other threads affected?
Can someone help me analyze this problem?
I also tried sending SIGCONT and SIGSTOP to all of the threads of the process but the issue still occurs sometimes.
Thanks,
Sandeep
Assuming you are using Linux, you should be using tkill(2) or tgkill(2) instead of kill(2). On FreeBSD, you should use the SYS_thr_kill2 syscall. Per the tkill(2) manpage:
tgkill() sends the signal sig to the thread with the thread ID tid in
the thread group tgid. (By contrast, kill(2) can only be used to send
a signal to a process (i.e., thread group) as a whole, and the signal
will be delivered to an arbitrary thread within that process.)
Ignore the stuff about tkill(2) and friends being for internal thread library usage, it is commonly used by debuggers/tracers to send signals to specific threads.
Also, you should use waitpid(2) (or some variation of it) to wait for the thread to receive the SIGSTOP instead of polling on /proc/[pid]/stat. This approach will be more efficient and more responsive.
Finally, it appears that you are doing some sort of stack sampling. You may want to check out Google PerfTools as these tools include a CPU sampler that is doing stack sampling to obtain estimates of what functions are consuming the most CPU time. You could maybe reuse the work these tools have already done, as stack sampling can be tricky to make robust.

Categories