I actually have three questions..
Let’s say I have a function called CalcualteAge() and this function is going to be called by several users (Lets think about this as a simple server application providing this function) then how would I handle concurrent function calls between users? (Ex. What happen if user A and user B call the function at the same time
Another question is that the function (CalcualteAge()) is running on a separate thread and it has a return value. Then how would I pass the return value back to the main thread so that main thread can return the value back to the person who called the function.
Last one is that which way is better to implement this? Should I create a new thread and run the function on the thread and terminate the new thread once it finish the calculation? or Should I keep the thread running on background as long as the the application is running?
Thanks in advance.
If you are doing work on a background thread, you can deliver results on the main thread using a
Handler. But the model of “return value from a function” is wrong. You need an asynchronous architecture. The most common one is a call-back functionresultAvailablethat can be called at any time after the background thread has done its job. TheAsyncTaskclass can help a lot with this.Whether to create a separate thread each time or keep a background thread running depends on how frequently you need this calculation done. You might want to use a producer/consumer model for this. There are many examples on the web of how to implement this in Java.
An alternative architecture, perhaps more appropriate for what you describe, is to set up your calculation code as a Service. Then you can “call” it by constructing an intent with the request and receiving the result. See the guide section on Services for details.