In a single-thread Android app, I registerReceiver
to update some global variables when the screen turns off.
Every minute, however, a timer triggers the running of a block of code which I do not
want to be interrupted. I know that there are "java.util.concurrent" tools to lock
execution to do exactly that, even if I were multi-threading, but I'd like to avoid
those complications if there are any Android guarantees about where my main looper
allows interruptions.
So, to help me understand the default behavior, does a registered receiver act ASAP
so that variables can get changed anywhere in the middle of my thread?
If so, I can easily put one or two "locking variables" in the code to reduce the risk
of problems, but taking that risk to 0% has a significant performance trade-off if
I deal with the race conditions inside my class. So, instead I am planning to use an
AtomicInteger
(which also of course has a trade-off, but potentially less since the Android OS can then schedule
interruptions in light of my given atomic requirements) for locking if I truly need 0% risk.
Or, is there a simpler solution for single-thread apps?
Related
Thread.stop() is now removed from modern Android API. From https://developer.android.com/reference/java/lang/Thread#stop(),
Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, ...
I suppose that a complete removal of a method must be backed by an alternative of it, both for the many uses where it is replaceable, and for the many other uses where it is not. I am therefore wondering what is the alternative of Thread.stop() that stops a thread where cooperative interruption flags do not work, which is possibly due to e.g. calls of slow 3rd-party functions.
From the articles I've googled and the duplicated SO questions I've read about this issue, I got only two unsatisfactory types of answers:
You should just consider cooperative interruption because it's not stupid.
Thread.stop() is now gone for whatever reason so just forget it.
I would appreciate a lot if you could either provide a functioning alternative of Thread.stop() or explain the rationale behind removing it despite the legitimate use cases depending on it, where "legitimate" implies nonexistence of any synchronization and locking issue.
Thanks in advance.
There is no "modern" alternative. The old alternatives are still the only ones. Why? Because this is fundamentally an unsolvable problem1 ... if the threads are not cooperating / checking for thread interrupts, or if they unable to correctly deal with a thread interrupt.
For the record, the technical reasons that Thread.stop() is unsafe include:
It breaks mutual exclusion locks help by the thread being stopped. This may leave the object that was locked ... or other objects ... in an inconsistent state.
It may result in broken inter-thread signalling. For example, if a thread is expected to notify a condition variable, and it gets stopped before this happen, then other threads may be stuck forever waiting for a notify that never arrives.
If has said that, issues such as the above can in theory be addressed by application code on a case-by-base basis. For example, if you were using stop() you could catching ThreadDeath in all of the necessary places, take remedial action and then rethrow it. But to borrow someone else's words, "it would be insanely messy".
I'm sorry if you think this is all unsatisfactory. But this is life. If you cannot write your threads to be cooperative, and you need them to be killable, run them in an external process, via Process etcetera.
Now ... if we could wave a magic wand and replace Java threads with a CSP-like model of concurrency (and in doing so, eschew state sharing between processes), then the problem goes away. Though now you have to deal with the other problem of what to do with the messages queued up when a process is terminated. But at least that is a tractable problem.
1 - I am asserting this without proof! However, if it was a solvable problem, then you would have thought that Sun or Oracle or Google would have discovered and implemented a solution in the last ... umm ... 25 years. Challenge: If you can come up with a viable implementation model for safely killing Java threads, I expect that certain companies would be willing to offer you a very well-paid job. Especially if they can secure exclusive rights on your patent.
My Main thread seems to be pretty bad with performance. Transitioning between activities results in significant delays. I have pushed all of Web/Bitmap/File work into AsyncTasks and yet this is still happening. I have been doing my head in trying to figure out what is causing the slow-downs.
My question is - If the Main thread uses a class (say ImageDownloader) that creates its own little AsyncTasks (say ImageDownloadTask), will Main wait for ImageDownloader to finish it's AsyncTasks (hence delays?)
I would love to post code, but it's a very large project. If there is anything specific I should look for, please let me know and I'll be sure to share.
If you haven't already done so, I recommend you enable strict mode and look for activity on the main thread that way.
Check your onCreates and onResumes for anything that might run for more than an instant. This includes network calls, database calls, loops that may have a lot of iterations, and even reading from locally stored files (SharedPreferences read from an xml). Also try to benchmark how long your onCreate executes the setContentView method -- I believe nested LinearLayouts cause significant performance hits especially in complex UI structures. Acquiring a location with the LocationProvider, when not done properly, will also cause severe performance issues.
You may think you are fine with passing off long-running threads on an asynctask, but you also need to check that prior to starting these tasks, the data you need to start them may take a while to acquire.
I designed a java application. A friend suggested using multi-threading, he claims that running my application as several threads will decrease the run time significantly.
In my main class, I carry several operations that are out of our scope to fill global static variables and hash maps to be used across the whole life time of the process. Then I run the core of the application on the entries of an array list.
for(int customerID : customers){
ConsumerPrinter consumerPrinter = new ConsumerPrinter();
consumerPrinter.runPE(docsPath,outputPath,customerID);
System.out.println("Customer with CustomerID:"+customerID+" Done");
}
for each iteration of this loop XMLs of the given customer is fetched from the machine, parsed and calculations are taken on the parsed data. Later, processed results are written in a text file (Fetched and written data can reach up to several Giga bytes at most and 50 MBs on average). More than one iteration can write on the same file.
Should I make this piece of code multi-threaded so each group of customers are taken in an independent thread?
How can I know the most optimal number of threads to run?
What are the best practices to take into consideration when implementing multi-threading?
Should I make this piece of code multi-threaded so each group of customers are taken
in an independent thread?
Yes multi-threading will save your processing time. While iterating on your list you can spawn new thread each iteration and do customer processing in it. But you need to do proper synchronization meaning if two customers processing requires operation on same resource you must synchronize that operation to avoid possible race condition or memory inconsistency issues.
How can I know the most optimal number of threads to run?
You cannot really without actually analyzing the processing time for n customers with different number of threads. It will depend on number of cores your processor has, and what is the actually processing that is taking place for each customer.
What are the best practices to take into consideration when implementing multi-threading?
First and foremost criteria is you must have multiple cores and your OS must support multi-threading. Almost every system does that in present times but is a good criteria to look into. Secondly you must analyze all the possible scenarios that may led to race condition. All the resource that you know will be shared among multiple threads must be thread-safe. Also you must also look out for possible chances of memory inconsistency issues(declare your variable as volatile). Finally there are something that you cannot predict or analyze until you actually run test cases like deadlocks(Need to analyze Thread dump) or memory leaks(Need to analyze Heap dump).
The idea of multi thread is to make some heavy process into another, lets say..., "block of memory".
Any UI updates have to be done on the main/default thread, like print messenges or inflate a view for example. You can ask the app to draw a bitmap, donwload images from the internet or a heavy validation/loop block to run them on a separate thread, imagine that you are creating a second short life app to handle those tasks for you.
Remember, you can ask the app to download/draw a image on another thread, but you have to print this image on the screen on the main thread.
This is common used to load a large bitmap on a separated thread, make math calculations to resize this large image and then, on the main thread, inflate/print/paint/show the smaller version of that image to te user.
In your case, I don't know how heavy runPE() method is, I don't know what it does, you could try to create another thread for him, but the rest should be on the main thread, it is the main process of your UI.
You could optmize your loop by placing the "ConsumerPrinter consumerPrinter = new ConsumerPrinter();" before the "for(...)", since it does not change dinamically, you can remove it inside the loop to avoid the creating of the same object each time the loop restarts : )
While straight java multi-threading can be used (java.util.concurrent) as other answers have discussed, consider also alternate programming approaches to multi-threading, such as the actor model. The actor model still uses threads underneath, but much complexity is handled by the actor framework rather than directly by you the programmer. In addition, there is less (or no) need to reason about synchronizing on shared state between threads because of the way programs using the actor model are created.
See Which Actor model library/framework for Java? for a discussion of popular actor model libraries.
What is both faster and "better practice", using a polling system or a event based timer?
I'm currently having a discussion with a more senior coworker regarding how to implement some mission critical logic. Here is the situation:
A message giving an execution time is received.
When that execution time is reached, some logic must be executed.
Now multiple messages can be received giving different execution times, and the logic must be executed each time.
I think that the best way to implement the logic would be to create a timer that would trigger the logic when the message at the time in the message, but my coworker believes that I would be better off polling a list of the messages to see if the execution time has been reached.
His argument is that the polling system is safer as it is less complicated and thus less likely to be screwed up by the programmer. My argument is that by implementing it my way, we reduce the reduce the computational load and thus are more likely execute the logic when we actually want it to execute. How should I implement it and why?
Requested Information
The only time my logic would ever be utilized would almost certainly be at a time of the highest load.
The requirements do not specify how reliable the connection will be but everyone I've talked to has stated that they have never heard of a message being dropped
The scheduling is based on an absolute system. So, the message will have a execution time specifying when an algorithm should be executed. Since there is time synchronization, I have been instructed to assume that the time will be uniform among all machines.
The algorithm that gets executed uses some inputs which initially are volatile but soon stabilize. By postponing the processing, I hope to use the most stable information available.
The java.util.Timer effectively does what your colleague suggests (truth be told, in the end, there really aren't that many ways to do this).
It maintains a collection of TimerTasks, and it waits for new activity on it, or until the time has come to execute the next task. It doesn't poll the collection, it "knows" that the next task will fire in N seconds, and waits until that happens or anything else (such as a TimerTask added or deleted). This is better overall than polling, since it spends most of its time sleeping.
So, in the end, you're both right -- you should use a Timer for this, because it basically does what your coworker wants to do.
I'm working on shoot 'em up game, that I'm planning on flooding the screen with entities, (Bullets, Mobs, and the like). I've tried a global timer to update everything on the screen, but I've gotten some serious fps drop when I flood the screen like I want.
So, I see myself as having two options. I can either give each individual entity a timer Thread, or I can section off the level into chunks and give each chunk its own timer.
With the first scenario, entities with their own timer threads, I will end up with hundreds of entities, each with their own thread running a timer.
In the section option, I will have multiple sections of the map with a timer updating multiple entities at once, with detections for when an entity leaves from one section to another.
I'm not familiar with Programming with Memory Efficiency in mind, so which method would be better for me to use?
You could try a ScheduledExecutorService.
It's part of the Java higher-level concurrency API. You can decide how many threads should exist (it re-uses threads for different tasks to avoid the overhead of creating new ones every time and is therefore expected to be much more efficient than creating new Threads all the time) or use a cached thread pool (which will create as many threads are necessary, but once a Thread has died it will re-use it to run new tasks).
Another advantage of this API is that not only can you run Runnables, you can also use Callables, which may return a value for you to use in the future (so you can perform calculations in different Threads and then use the result of each Thread for a final result).
I was experimenting with something similar and don't have a definite answer. But maybe some of the feedback I got from Java-Gaming.org will be helpful or of interest.
What I tried was this: each entity has its own thread, and collisions are handled via a very detailed map of the screen (basically a second version of the screen). Then, I have another thread that handles the display of the screen.
An "early" version of this, with over 500 entities being animated, is online:
http://hexara.com/pond.html
Later versions use more elaborate shapes and borders (rather than letting entities die and freeze at the edges) and collision logic such as bouncing off of each other and gravity. I was also playing with sprite aspects like "firefly" blinking. I mention "actors" on the web page, but the code isn't strictly that.
Some folks at java-gaming.org strongly thought having so many threads was not efficient. There was a lot of interesting feedback from them, which you might be interested in exploring. I haven't had time yet.
http://www.java-gaming.org/topics/multi-threading-and-collision-detection/25967/view.html
They were discussing things like hyperthreading and the acca framework for Actors.