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.
Related
If I want to make a request from an Android device to a remote service, I can use AsyncTask, AsyncTaskLoader, Intent, etc to make the a request apart from the UI thread. It seems there are a lot of options, but I am confused how to choose among them. Could you explain when and which to use? Also, are there any other options besides the ones I have mentioned?
This is an extensively discussed question, since Android provides a long list of mechanisms capable to handle service calls asynchronously, besides the one you mentioned there's also:
IntentService
Native Threads
Now, the key point in your question is "When to use it" and here would be my answer:
In software the only golden rigid rule is the "It depends rule", there's no hard rules for anything in software development there's always different ways to approach a problem in software (i guess that's the reason of the word "soft" in it...) and that's exactly why it always depends, it depends on whatever you need and although one approach might be the most common way to do it like for example "AsyncTask" it doesn't mean at all that AsyncTaks is always the way to go, it always depends on the factors and needs that affect your functionality. There's plenty of things that nowdays get executed using AsyncTaks when maybe all you need could be just a regular common Native Thread.
The only way to be able to make a decision towards the most appropiate approach would be knowing ALL the features around a tool, like for example most people 90% of the time use AsyncTaks just to run doInbackGround on separate thread, but might not even need preExecute, publishProgress, postExecute, etc, and that's something a Regular Thread could do, just like this example there's features for every single object provided in order to do remote calls, however as i already mentioned several times, it all depends on what you need and what tool fits better your needs. Remember there's no hard coded rules for "How, When, and What" to use in software, IT ALL DEPENDS, and making good decisions in that "DEPENDS" makes the difference between good developers from excellent developers...
This is a list of things i usually take on count to implement either one way or another, this list do not apply for all the scenarios but might give you an idea.
AsyncTaks- I know is a good idea to make use of asynctaks when the functionality needs to be monitored, by monitored i mean, i need to keep track of progress during my job, like (download/task progress), because that's exactly what the AsyncTask was originally created for, it was created attached to "The Task Pattern", and if i don't need to make use of at least two methods for monitoring provided by AsyncTaks like onPreExecute,onProgressUpdate, onCancelled etc. I know there might be another way to implement it.
Native Java Threads - I know is good to make use of this tool when my task is not related to any view in android at all, and do not need to be monitored (example: removing/adding data from remote database, and the response might affect just persistence elements that will not be displayed like configuration preferences)
IntentService - When i want to do a one time task in a queueprocessor fashion way, but unliked a native thread, here i would like to have some application context in order to maybe bind an activity etc...
Regards!
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.
I am a complete noob to android but I have been programing c# for a long time. I am writing an android application and have gotten to a point where the c# programmer in me wants to start creating a loosely coupled design and and moving code into different layers, using interfaces, etc.
But then I stumble upon the Designing for performance guidelines it is telling me to avoid object creation and then it also is saying to optimize judicially.
Do I just build based on good design and then deal with performance issues as they come up?
The last thing I want to do is go through the work of building a application and have it perform poorly. Can someone point me to some examples of application that are designed well and have good performance or just make some recommendations?
Thanks
I've found AndEngine to be fairly well designed and it has to be concerned with performance since it is a game development library -- so you might pull down a copy of it and read the source.
In the "Designing for performance" document, I would point out this statement:
Note that although this document
primarily covers micro-optimizations,
these will almost never make or break
your software. Choosing the right
algorithms and data structures should
always be your priority, but is
outside the scope of this document.
An example of this would be creating a particle system. A good way to model it is to have a ParticleSystem object that holds a collection of Particle objects...maybe those Particles implement a Particle interface...this is not the place to avoid object creation. However, for performance reasons, you will want to optimize the ParticleSystem to recycle Particle objects rather than creating them from scratch every time you spawn one.
Personally, I haven't found performance to be much of a limiting factor but I suppose that will really depend on what type of app you're building.
My opinion is to build a suitable design first, test the performance, and optimize from there.
Pay more attention to Donald Knuth's quote that appear in the same article:
"We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.root of all evil."
Then if you are dealing with the other 3% you'll see...
As a general rule, the thing to do is keep the data structure as simple and normalized as you can. Like don't just throw in hash table data structures just because they are easy to grab. Know how to do profiling (here's my method) and if you have a real performance problem then fix it. Otherwise, the simpler the better, even if that means simple arrays, lists, and O(N) loops.
The reason to keep the data structure normalized is, if it is not, then it can have inconsistent states, and you will have a strong temptation to write notification-style code to try to keep it consistent. Those can be real performance killers. If you do those, the profiling will tell you it that's what is happening.
If you must have redundant data, I think it's better to be able to tolerate some temporary inconsistency, that you periodically repair by passing through the data. This is better than trying to intensely guarantee consistency at all times by notifications.
Another problem with unnormalized data structure is it can have lots of object creation and destruction. That also can be a real performance killer, although you can ameliorate it with the pool technique.
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.
Are there pitfalls or the points to remember while programming for Android? I think the list will include topics on Multithreading, Persistent Storage, etc.
There are many things that could be said here.
The Android videos from Google I/O 2009 cover most of the aspects that should be kept in mind, when programming on Android. In fact, the http://android-developers.blogspot.com/ articles are the source, on which these presentations expand, and seeing them explained from some of the best Google engineers (and as a bonus you'll get a Q&A section) is a must for every Android developer, IMO.
Some of the things that could be mentioned:
Don't use floats, when you can achieve similar results with integers, because Android doesn't have native support for floating point values.
Use the debugging tools extensively, to optimize both performance and maintainability, and to avoid common pitfalls like ViewGroup redundancy in UI design, or unnecessary multiple calls to heavier methods (View.inflate(), findViewById(), setImageResource()).
Bundle your background service calls, otherwise you are waking up the OS unnecessarily and too often, while risking other services piggy-backing your call (which results in severely reduced battery life)
Prefer SAX-parsers over DOM-parsers, you lose time while implementing them, but you win time in your app's performance (and your device's availability)
Keep your UI manipulations on your UI thread, because the interface toolkit is not thread-safe
Keep in mind that orientation change destroys and creates your Activity again (I learned that the hard and painful way - this is how I started to follow the android-developers' blog)
...and many others.
Android Developers has good post about avoiding memory leaks due to keeping Context references. There are a lot of other interesting posts there too.
I wouldn't call them pitfalls per se, but always remember to take into account that this is not a computer that's plugged into a wall that can just be upgraded in various ways. You have an upgrade cycle of about every 2 years (the length of a standard mobile contract these days) and the hardware is (A) not the fastest and (B) static during that time.
Things to take into consideration:
1) How does the things your app does affect battery life? Are you splashing bright graphics all over the place? Running a lot of threads in the background? Services?
2) How much space does your application need to take up on the device? Is the information something that can be kept on a server and transmitted to the device for temporary use only when it's needed?
3) In regards to #2, is your app tolerant of bad/nonexistent network/mobile connections? How does it perform on the EDGE network vs 3G?
I'm sure you can come up with more but this is what I keep in mind while I'm writing my apps.