two android threads and not synchronized data - android

i have a (perhaps stupid) question:
im using 2 threads, one is writing floats and one is reading this floats permanently. my question is, what could happen worse when i dont synchronize them? it would be no problem if some of the values would not be correct because they switch just a little every write operation. im running the application this way at the moment and dont have any problems so i want to know what could happen worse?
a read/write conflict would cause a number like 12345 which is written to 54321 and red at the same time appear for example as 54345 ? or could happen something worse?
(i dont want to use synchronization to keep the code as fast as possible)

The worst that could happen is that your reader thread never sees anything your writer thread has written. There is no guarantee that memory written to by one thread will ever be seen by another thread without some form of synchronization.

If one thread is writing to a particular float and changes the value from 'a' to 'b', another thread reading the same float will only see either 'a' or 'b', never a third value.
As for any other potential logic problems your app may experience, it is impossible to answer this without knowing more about your app.

Worst case is that your users find you application is errant because it does not behave properly due to concurrency issues.
Uncontested locks do not add much overhead. You should always write an application correctly first and then optimize only after running metrics which indicate where you're problem areas are. I'd wager that a lot of your application code is likely to be the source of performance issues rather than some basic synchronization.

Related

Android Traceview - It holds the Answers to my Unresponsive App... I think

Yesterday, I spent 12 hours becoming a student of Traceview. I didn't even know it existed (hangs head in shame) previous to this.
Now that I've overcome the absolute shock of the data it produces, I find Traceview can be boiled down into a couple simple concepts:
Sort by "EXCL CPU TIME" to determine exactly how much usage each individual method is using in isolation.
Look at the frequency of calls and the cpu time/real time per call. Obviously higher calls should be looked into. In most of my experience, if you sort by #1 above, methods which are called too much and take too much time will also be at the top of the list (makes sense as they are also using the most CPU).
Anyway, doing these two steps above I find 3-4 methods which are always using 90% of my CPU and taking up most of the real time delays in my app. The only problem is, none of these methods are methods I wrote, they are system methods such as:
BitmapFactory methods
WebKit methods
And other system methods
This being said, is it a correct to assume that if the top resource hogs are system methods, then it must have something to do with my design of my layouts? I am at a loss as to how BitmapFactory could be so high, my layouts aren't extremely complicated, though in one Activity BitmapFactory is taking 95% of resources itself.
TL;DR - If I run a Traceview, and if I find the top hogs of resources are all system methods, does this mean it's a layout issue? Or, how else can I tell why the system method is so high as it doesn't relate directly to my custom methods.
Thank you very much,
Ryan
I find Traceview can be boiled down into a couple simple concepts:
Those concepts are not the best, IMHO.
Sort by "EXCL CPU TIME" to determine exactly how much usage each individual method is using in isolation
In particular, this concept is fairly lousy IMHO. Yes, this is useful data. However, you then need to work back up the call stack to try to figure out what is triggering this. Sometimes, it will directly be your code. Sometimes, it will be something else that you recognize that is part of the framework (e.g., onDraw() of a View). Just knowing that some random method is taking up a bunch of time does you no good until you identify what is triggering that method to be invoked in the first place.
If I run a Traceview, and if I find the top hogs of resources are all system methods, does this mean it's a layout issue?
No.
Or, how else can I tell why the system method is so high as it doesn't relate directly to my custom methods.
Work your way up the call stack to figure out who is calling these methods so frequently, or at inopportune times.
For example, in the BitmapFactory example, you will probably find that you (or a library that you are using) is calling BitmapFactory, and perhaps is doing so on the main application thread.
To work your way up the call stack, click the triangle on the left edge of the row representing some method of interest. You will then see two branches beneath that: "Parents" and "Children". The "Parents" represent the next level up the call stack from the method, and you can continue working your way up the chain of parents until you find something that you recognize.
That's why, IMHO, you are better served sorting by inclusive time, as your code (where it directly is the culprit) will tend to bubble towards the top.
Well, I found the problem and it's bitter sweet. It's sweet because it wasn't my code nor layout causing the problem, it was the admob AdView using the loadAdOnCreate="true" to create ads. It's bitter, because I now may have to switch sources of revenue if I can't remove the loading delay created by the AdView! That was a tough one to find, I should have anticipated this though!

Android: Why not make every method Synchronized?

Is there any downside to making every one of your methods synchronized in Android?
Yes - it will end up taking out locks when you don't really want them. It won't give you thread safety for free - it'll just slow down your code and make it more likely that you'll run into deadlocks due to taking out too many locks.
You need to think about thread safety and synchronization explicitly. I usually make most classes not thread-safe, and try to limit the number of places where I think about threading.
The "make everything synchronized" approach is a common one in what I think of as the four stages of threading awareness for developers:
Complete ignorance: no synchronization, no awareness of the potential problems
Some awareness, but a belief that universal synchronization cures all ills
The painful stage of knowing where there are problems, and taking a lot of care over getting things right
The mythical stage of getting everything right naturally
Most experienced developers are in stage 3 as far as I can tell - with different levels of ease within it, of course. Using immutability, higher-level abstractions instead of the low-level primitives etc helps a lot - but ultimately you're likely to have to think a fair amount whenever you've got multiple threads which need to share state.

Game Object Thread?

I'm trying to develop a game. It's a simple whack-a-mole type of game where something pops-up the screen and you click on it to kill it. I was thinking of giving the "moles" their own thread so that they can do their own animation, event handling, etc. in their own lifecycle until eventually killing themselves.
Will this kind of "each object has its own thread" implementation be good for an Android game?
Definitely not. Do not give each mole its own thread. This would be too much use of threads while it is needless to say that in this type of game you do not need such a number of threads. Just keep everything in the main thread and use some listeners to kill moles. (=make invisible)
Yes, it is a performance issue and a matter of developer's decision. Why should you create a thread for each mole? This is the right question because doing so is a far more unrealistic decision. Will each mole access a database? communicate with a server? I don't think so.
Anyway, since it is a mole on the screen, you will only need one instance of it that you can render/move it around/disable/etc in the main thread.
This could work, if there aren't a ton of objects, and a ton of activity for each object.
I would suggest thread pooling. Pull out inactive objects out of threads and put in active threads.
Stay single threaded until you actual need to change - especially for a simple game, you won't have the kinds of performance problems that need threading.
At any rate the general approach is not to thread out individual entities, but entire steps of algorithms performed across 100s or 1000s, or even entire systems (e.g. audio, physics etc.) - and perhaps the most extreme but common case is to split your rendering submission into its own thread for all rendering, with animation, physics, gameplay logic etc on another thread, in exchange for single frame latency on everything.
Not to mention that the overhead of having very many threads often becomes limiting - if you have 2 or 3 moles it might be fine, but if you have many more you will quickly reach the point of diminishing returns - not to mention the difficulties inherent in keeping many threads in sync and avoiding deadlocks, race conditions etc.

producer consumer

i have an application which has a part where some variables are written and read at very high frequency.
Is there any need of a semaphores or locks(Data consistency is not a concern in this case).Is there any chance of application terminating or crashing.I dont want to get into threads,semaphores and stuff as it is a trivial part of application.
There is not nearly enough information in your question to give you an accurate answer, but in general - if you have multiple threads, and one produces data, one consumes it, then yes, you will need synchronization.
You could use a BlockingQueue, or just a simple synchronized object, whatever is appropriate in your case... but you will need some synchronization, or else you risk random hard-to-reproduce crashes.
This is even more important when dealing with multi-core systems, which are becoming popular now.

Android Database Locking Behaviour

I still haven't really wrapped my head around synchronization. I know it's there, I know why it's used and what the idea is behind it, but Im lacking the practical skill and real world examples to understand exactly how it works and how it's implemented when several activies are trying to read/write to the database at the same time. Do you share your objects through Application, or is the system intelligent enough to synchronize various objects of the same type?
Perhaps a Content Provider is a better way to go as I understand that has built in sync.
I digress though.
Im still confused over database activity. Remember that I have a service running every 60 seconds in the background reading the same table an update function is writing to. Yes Im looking to change this, but right now I want to understand database handling in Android more and work out what's happening.
If I have a loop such as:
db = provider.getReadableDatabase();
while(theres_still_work_today) {
do_some_calculations;
update_database;
}
provider.close();
this works fine as a standalone. If I try and place this in a thread, I get errors galore about locking. But when run like this:
while(theres_still_work_today) {
do_some_calculations;
db = provider.getReadableDatabase();
provider.close();
update_database;
}
I find that bizarrely, this actually seems faster, and gives no locking issues.
Am I just being incredibly lucky that I don't get two events triggering at the same time causing a lock? Is there some kind of timeout built into database handling in Android/SQLite?
I don't understand why the last bit of code should work OK, and why it should work faster?
Im not entirely confident about the Android Emulator though. If I use the first option with a single open/close outside the loop, sometimes I can get through a long long loop fine even though the service triggers in the background.
Other times it crashes on a whim.
I also don't know why "isDatabaseLockedByOtherThreads()" does not report that it is locked by other threads.
Any advice?
Thanks
Simon

Categories

Resources