Use of global variable in never ending service - java

I created a never ending service but I'm not sure that it's OK to do what I did with this service. I declared global variable like static String list_contact
and fill the list from a db in onCreate method. I wanted to avoid to retrieve data from database each time because I need to compare to the list fast. But maybe it's a problem to store data in global variable of Service. Plus I need another list with thousands of data. If it's no good, can I find a compromise between memory and speed for retrieving data ? Thanks.

Its not a great idea put the static variable in Service and assume that service would run forever.
The biggest drawback is, service won't run in background forever, starting from Android O. Latest version applies more restrictions on the background processing and kills your service few minutes after app is put in background.
You can implement Object pool pattern which will store the frequently accessed data in an Object. This doesn't require to have a service running and could serve your purpose. You need to ensure that you are not maintaining sensitive data in clear text in these Objects.
Alternatively, you can also read this post which describes caching for Android.

Related

Global object (based on "extend Application") evaporates overnight.. why?

I have an android app where I extend the application object as such
public class Globals extends Application {
private Map<String, Object> Creators = new LinkedHashMap<>();
}
Globals has various things in it. usually HashMaps of things - I use it as a global json cache where each Context has an instance of this. Now overnight it appears the Application object can sometimes be empty. i.e. I use the app go away and go to sleep, go back to testing it in the morning and all the json caches are empty. But the user is still "logged in". I assume this is because of garbage collection on the OS.
Now. I could just refresh the json cache or force "logout" when the json cache is empty but there is a problem - it may be empty because there IS legitimately no json from the server. i.e "being empty" is no reason to go get more. What I need to be able to do is detect when android has flattened the cache, or at least know the minimum amount of time that Android will keep the Application extension.
Would it set everything to null?
Has anyone got any ideas? Bear in mind the context will re-initialise null HashMap members of the Application in the context in onCreate (which is required for reason outside the scope) because I declare the new but simply testing for "null" is not really an option. I suppose making a blank null that is changed only on json gather would be ok but I need to KNOW this will work or I lose yet another day chasing this (i.e it's VERY hard to test)
Now overnight it appears the Application object can sometimes be empty. i.e. I use the app go away and go to sleep, go back to testing it in the morning and all the json caches are empty.
Your process was terminated, most likely. See the documentation and the documentation.
What I need to be able to do is detect when android has flattened the cache
You are not informed when your process is terminated.
or at least know the minimum amount of time that Android will keep the Application extension
Your process can be terminated milliseconds after it leaves the foreground.
[Application works] fine as a data store
Only for data that you can easily reload from a persistent data store.
[Application] works works on multi thread
Only if you add your own thread-synchronization logic. There is nothing magic about properties and functions on Application that makes them thread-safe.
where there is no place to store mutable data - this is the best alternative
Any data that you wish to keep should be stored on disk (database, SharedPreferences, or other types of files) or on a server.
so my question remains how to mitigate it
Any data that you wish to keep should be stored on disk (database, SharedPreferences, or other types of files) or on a server. Use in-memory caches as caches.
because things like SQLite are useless they're not thread safe
If you use the same SQLiteDatabase instance for your operations, SQLite is thread-safe.
effectively making it impossible to run anything in parallel
You are certainly welcome to use other persistent data stores if you find SQLite to be distasteful.

How to make a web service in java that can be called by multiple users

I have a simple Web service in Java and Weblogic. In this web service, I have a method which receive some data, call another webservice, write in DB and then answer with result.
If I try it with only one call it works fine, but, if I've tried with Soap UI, creating a TestCase, where you can call the web service in multiple threads, sometimes, it works ok, but sometimes, when there are a call in the middle of another, the result is not correct.
The problem is that when I call web service method I init some variables I have to analyze and save in DB, so, if a call is interrupted, these variables are updated and when the first call finish, the result is not correct (they are with init values).
If I put synchronized in web service method it works, but I think it's not the best way to do it, because I want to allow multiple users at the same time.
What's is the best way to do this?
Thank you very much
when you start writing client specific applications, you're required to keep a data for client state in your DB.
So, when each client accesses your web server with their cookie/session, you can get the client-id (encrypted in side cookie/session) and evaluate server-side parameters based on values of client in DB.
Thank you to kolossus comment, I've solved it removing global variables and creating only local variables, so each call will create a new variable and not overwrite common variables.

How to approach JMX Client polling

recently I dove into the world of JMX, trying to instrument our applications, and expose some operations through a custom JMXClient. The work of figuring out how to instrument the classes without having to change much about our existing code is already done. I accomplished this using a DynamicMBean implementation. Specifically, I created a set of annotations, which we decorate our classes with. Then, when objects are created (or initialized if they are used as static classes), we register them with our MBeanServer through a static class, that builds a dynamicMBean for the class and registers it. This has worked out beautifully when we just use JConsole or VisualVM. We can execute operations and view the state of fields all like we should be able to. My question is more geared toward creating a semi-realtime JMXClient like JConsole.
The biggest problem I'm facing here is how to make the JMXClient report the state of fields in as close to realtime as I can reasonably get, without having to modify the instrumented libraries to push notifications (eg. in a setter method of some class, set the field, then fire off a JMX notification). We want the classes to be all but entirely unaware they are being instrumented. If you check out JConsole while inspecting an attribute, there is a refresh button at the bottom of the the screen that refreshes the attribute values. The value it displays to you is the value retrieved when that attribute was loaded into the view, and wont ever change without using the refresh button. I want this to happen on its own.
I have written a small UI which shows some data about connection states, and a few field on some instrumented classes. In order to make those values reflect the current state, I have a Thread which spins in the background. Every second or so the thread attempts to get the current values of the fields I'm interested in, then the UI gets updated as a result. I don't really like this solution very much, as its tricky to write the logic that updates the underlying models. And even trickier to update the UI in a way that doesn't cause strange bugs (using Swing).
I could also write an additional section of the JMXAgent in our application side, with a single thread that runs through the list of DynamicMBeans that have been registered, determines if the values of their attributes have change, then pushes a notification(s). This would move the notification logic out of the instrumented libraries, but still puts more load on the applications :(.
I'm just wondering if any of you have been in this position with JMX, or something else, and can guide me in the right direction for a design methodology for the JMXClient or really any other advice that could make this solution more elegant than the one I have.
Any suggestions you guys have would be appreciated.
If you don't want to change the entities then something is going to have to poll them. Either your JMXAgent or the JMX client is going to have to request the beans every so often. There is no way for you to get around this performance hit although since you are calling a bunch of gets, I don't think it's going to be very expensive. Certainly your JMXAgent would be better than the JMX client polling all of the time. But if the client is polling all of the beans anyway then the cost may be exactly the same.
You would not need to do the polling if the objects could call the agent to say that they have been changed or if they supported some sort of isDirty() method.
In our systems, we have a metrics system that the various components used. Each of the classes incremented their own metric and it was the metrics that were wired into a persister. You could request the metric values using JMX or persist them to disk or the wire. By using a Metric type, then there was separation between the entity that was doing the counting and the entities that needed access to all of the metric values.
By going to a registered Metric object type model, your GUI could then query the MetricRegistrar for all of the metrics and display them via JMX, HTML, or whatever. So your entities would just do metric.increment() or metric.set(...) and the GUI would query the metric whenever it needed the value.
Hope something here helps.
Being efficient here means staying inside the mbean server that contains the beans you're looking at. What you want is a way to convert the mbeans that don't know how to issue notifications into mbeans that do.
For watching numeric and string attributes, you can use the standard mbeans in the monitor package. Instantiate those in the mbean server that contains the beans you actually want to watch, and then set the properties appropriately. You can do this without adding code to the target because the monitor package is standard in the JVM. The monitor beans will watch the objects you select for changes and will emit change notifications only when actual changes are observed. Use setGranularityPeriod to tell the monitor beans how often to look at the target.
Once the monitor beans are in place, just register for the MonitorNotifications that will be created upon change.
not a solution per se but you can simplify your polling-event translator JMXAgent implementation using spring integration. It has something called JMX Attribute Polling Channel which seems to fulfill your need. example here

Best practices to get data and save it

I have an android application and in one of my activities I am making a call to get say "Customers", this call is made to an external API, when I get the response I get it as a JSON object. The problem i am having is that I have a ListView in the activity and when you click on of its items it shows you the details but then when you hit the back button I have to make the call again to populate it. In Samsung Galaxy 4S it seems to keep the data of the list view but in the HTC android incredible it's blank. So what I did is, make it rebind OnResume(), this fixed the issues for both BUT the consequence is making another call to that server. When its 10 or 100 customers it doesnt matter but I know that there are some accounts that have up to 5000 and I am sure it will crash.
What are my options to improve performance on this issue with Android?, I tried a static variable but at some point that object got cleared too.
How do Android applications usually handle this cases where the data is retrieved from API's and they need to be stored through out the application and there is no need to make another call for the same information?, I was thinking on static object but i want to make sure I do this the right way.
You have a couple of options.
1) You can cache the data in memory. For example you can make a static cache or cache the data within the Activity or the App object. If you are doing this in only one view and if it is not a lot of data, this might be an ok solution. However, if you have to do this for many activities and there is a lot of data that has to be cached, you might want to go for option 2. Also storing data in memory in android, does not mean it won't be garbage collected (in some cases, even if you have a reference to it.)
2) You can cache the data in the internal storage and refresh it from time to time.
You can find more info about the internal storage and how to use it here: http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
Basically, you store the response within the internal storage under a specific identifier. The next time you open the activity, you check if the storage has data for that identifier and if yes, you read it and display it. If no, you make the API call.
Keep in mind, that you will have to refresh the cache from time to time.
I had the problem with ListViews on my application too. What I did is that I wrote a custom adapter and that solved the issue..
However the thing you can do is to make a global variable and save the returned results to it. When your application wants to call the server, check the variable, if it's null make the call, if it's not then just draw the ListView with the already fetched data..
Keep in my mind, to implement a refresh button, you need to skip the check.

How to apply static class in php

I am java and php programmer.
In java i can use static class/method so that anyone can use the same one time created class during run-time.
But for php how to do it since it is script based and only run while we refreshing the page?
My main objective is, I want to use syncronized class/method so that it wont clash while executing the PHP...
Need your help to give input.
Thanks
Update:
I am doing portal like multi level marketing(mlm)
Once register a member, we should pay bonus to the uplines
I don't want immidiately calculate the bonus because it is risky and could take some time to finish, so is is better just to register the member and show successfull.
My idea is, after registration, just invoke another class to run bonus with syncronized method so that the bonus calculation will not disturb by another registration.
Given that a php scripts runs from new every sinlge time a "static" class would not be very different from an ordinary class.
If you want to store some sort of state or preserve some data between runs of a php program then there are a number of options.
SESSION variables can be used to store data between requests from a single users as long as he keeps the session open.
COOKIES can be used to store data which persists between sessions as long as the user is using the same browser, on hte same machine and hasnt emptied the cookie jar.
memchached and similar packages can be used to store data and make it available to any php program on the server.
Databases are the most scalable solution as they will persist data between sessions, and between servers. There is some overhead involved is establishing connections and retrieving the data compared with the other solutions.
PHP is shared-nothing. Everything just lives for the Request. If you want to share information between Requests, you have to implement some additional technology layer that can do so. Or look into process control, shared memory segments and semaphores. The latter three are uncommon usage in PHP though. And all of the above will still be asynchronous.
To my knowledge, there is no way to update class Foo in one Request and have it change state immediately in a concurrent Request with PHP.

Categories