issue with appengine dynamic instance - java

I have a class which does something (initialization ) when my app first starts.This initialization code is present in static block .So normally should be executed only once when the class loads for first time.
Now when the problem is as my instance is dynamic when there are no requests coming to my server my app gets unloaded .So next time when a request comes app is loaded dynamically and initialization code runs again.This is what i dont want.
I know this problem can be solved by using resident instance.But i guess resident instance is not available in free quota.Correct me if i am wrong.
Is there any way by which i can get away with this problem?
Storing the result of calculation in db is one option buts its not feasible as i want that data quickly?
How about memchace?Will it work?Will the data in memchace preserverd across dynamic loading of my app?
Note:I am not explicitly unloading my instance but app engine does it when my app doesnot get any requests.

Memcache data can disappear at any time. Only datastore data is guaranteed to be persistent.
You can store your initialisation data and fetch it in the order:
static data members(?)
memcache data
datastore data
(this is what I do) if you don't want to take up Nick's suggestion.

Or you can schedule a task that periodically runs every 10 minutes, this instance will be kept loaded. (ensure to have threadsafe on)

Related

Activiti BPMN Engine: store custom property in Database

i use the latest Acitiviti 5.22.0 engine (to be more concrete i use Alfresco Process Services 1.6.3) and i have implemented a Spring bean that gets executed every 10 minutes to generate a JSON representation of all my processes (process name, startDate, endDate, current taskName(s) and assignee(s)), to send them to an audit server. The problem is, that i only need to send all changed processes since the last run.
I do not want to send the JSON as soon as a process changes but to do a batch update of my audit system every 10 minutes.
To accomplish this, i've tried different approaches. My latest one:
Create a event listener bean that listens to all PROCESS_STARTED, PROCESS_COMPLETED, PROCESS_CANCELLED, TASK_COMPLETED, ...
Every time the event is triggered, store a process variable "_dirty" and set it to true
Every 10 minutes (wenn my JSON-bean is executed) query for all processes with the "_dirty" variable set to true
After sending the JSON to the audit system, set all "_dirty" process variables to false.
The problem with this approach: I am not able to update the "_dirty" variable after a process is ended. At least i don't know how.
My second approach would be to to store the processInstanceId on every event into a "global" property, but i don't know how to store this "global" property into database in case the server restarts. Is there a way to persist a property or an Entity into DB without creating an extra table, DAO, etc.?
Any ideas on how to solve this task? All tips are very much appreciated!
AFAIK, There's no such option
But you look at this. and see if it can be helpful in your case.
https://www.activiti.org/userguide/#_database_tables
As Linus suggested: This is not possible, so I needed some completely different approach.
I am creating an Ad-Hoc task now and store my properties as a local task variable. The Ad-Hoc task is owned by a system account and not assigned to anybody. This way I can make sure, no one of my real users tries to "complete" the task. Also I've written some code to generate the task if needed, so in case i want to clean it, it is created automatically the next time i want to store data.
Creating an Ad-Hoc task is quite easy by using org.activiti.engine.TaskService autowiring into my class.
Task task = taskService.newTask();
task.setDelegationState(DelegationState.PENDING);
task.setName("Some name goes here");
task.setTenantId("your tenant id (if any)");
task.setOwner("your system accounts ID");
task.setCategory("i use a special category to later query for the task");
taskService.saveTask(task);
After saving the task to the database, I can use the taskService to store and retrieve variables like this:
taskService.setVariableLocal(task.getId(), "variableKey", "variableValue");
Or query for the task like this:
Task task = taskService.createTaskQuery().taskDelegationState(DelegationState.PENDING).taskCategory("your special category").singleResult();
Not a very nice solution (I recommend having the task cached in a bean or something, so you don't need to query it all the time or even cache its values or something), but it works.

Best strategy to persist configuration variables of a JSP web aplication?

I'm implementing a web application using java (jsp). Now I'm adding some configuration buttons into the application, and i need to know which is the best strategy to persist them.
For example, I need to add a switch which will tell if each 10 jobs with errors the main worker must be stopped. It is a boolean variable called "safeStop". For that i need to persist if that config value is activated. This persistent value must be there even if the server is reset so it is not enought to persist it on RAM, it mus be persisted on disk.
This application will process thousands of works at day, so I need a safe and efficient way of persisting configuration.
I can't find any coherent info about different strategies of doing this and which is the best option. Any help or strategies will be helpful.
Thank you
I think the best practice would be to keep all the conf variables in a database and set a cookie on client side if that data needs to be processed. Once operations are performed update the values on server on session end or after a certain time or data volume or at the end when all processing operations are complete. This way you'll achieve performance, store information on something besides ram while using the RAM for shorter transaction operations

What is the lifespan of a private variable in an GAE Endpoint class?

I have the following code for an instant messenger style app.
public class MyEndpoint {
private Integer numberOfConvos=0;
...}
then I update it like this:
#ApiMethod (name="createGroup")
public myModel createGroup(#Named("profile") String profile){
numberOfConvos=numberOfConvos+1;
}
So everytime I make a new chat, I can make a unique and increasing ID.
If I redeploy the backend (bug fix for example) would the variable be reset? I do not want to store this one token in the datastore, because it doesnt seem needed and datastore charges for reads/writes.
If it would be reset each time I deploy, what is the correct way to keep track of this variable?
If is does not reset when I redeploy, how could i force it to reset?
A non-static variable is initialized for each thread. Several threads can be running on the same App Engine instance and your Cloud Endpoint service can be running on several instances in parallel.
So let's say that given the current load, you Cloud Endpoint service is served through 3 instances I1, I2, I3. Let's also say that each instances run 5 threads. In that case you would have 15 different versions of numberOfConvos with 15 different values.
Keep also in mind that instances can be turned on or off by Google at any time, in which case your service would be moved to a different instance. This would reset the numberOfConvos variable.
To put it more generally : your java code should be stateless, you should not store state between requests in a variable, even a static one.
You have two choices here :
If you do not want/need to keep track of the number of convos on the server and just want a way to uniquely identify each convo, then use the UUID class to generate a unique id for each convo, with very low risk of collision. The documentation is here but a typical code would be :
UUID.randomUUID().toString()
If you want to keep track of the number of convos, or persist the convo ids on the server, your only choice is to use a database such as App Engine's datastore to keep track of the variable. If you're new to this subject, I suggest you read a bit about transactions, otherwise you will not be able to manage the state correctly. Note that App Engine can generate ids automatically for you.

How to check for updates while app is closed in Android?

So here is my case. I have one main activity and when I start it I fetch some data from a local server via JSON in an AsyncTask and store that data in an ArrayList.
Also when I launch the app I start a service which is polling data from the server every X seconds. I use an intent to send that arrayList to the service so it can compare and see if there are any changes. The service is supposed to run all the time even if the app is closed.
All that is managed so far but I did a big mistake not storing the initially fetched data from the activity in SQLite or something like that.
Do you think its a good idea to do that ? Using SQLite for checking for updates ?
I also forgot to mention that if I close the app and when the service tries to compare it gets a nullpointer because I assume the activity does not exist anymore once I stop it.
I am open to suggestions.
If your data is simple enough, just try storing it in SharedPreferences. It'll avoid a lot of SQL headaches.
You can just fetch that data from the service instead of using Intents as well. Keep it simple!

getting data from a database vs getting data from a hash map

In my android *project* I have to keep track of product details of certain number of products. All the data on these products are store in a SQLite database. I can use select and update in SQLite to perform keep track of product objects. So I can store product details when ever they are changed.
Also I can load all the products into a hash map or such a data structure at the beginning and keep track of those product objects.
what matters to me is out of above both which one is more efficient and productive. Can someone help me. Thank you!
This depends on the number of products. A HashMap resides in RAM, a database resides on the disk.
This also depends on the number of queries per second and the nature of the queries. Database developers have put a lot of effort to support indexing and filtering; if you need that, reuse is better than re-inventing.
Whatever approach you choose, you must remember that an Android application process may be killed at any moment (e.g. when memory is needed for another process), and your code is guaranteed only to receive onPause() (and not onDestroy() or onStop(), see the activity life cycle). If necessary, the application will be restarted later, but all data kept in RAM (and not saved) will be of course lost. Therefore, in either onPause() or in onSaveInstanceState() (what bundles are for) you must save the application state. In your case this may mean having to save the HashMap and all auxiliary data structures.
OTOH, if the number of products is small (and is expected to remain small), a database can be an overkill; if you just need to choose one of 10 items, writing a loop is faster than doing all the database support.
One more important note: an Activity is a Controller from the MVC viewpoint (and as to the View, you usually create and XML and reuse the existing framework classes, although you could program custom controls). An Activity is re-created each time the device orientation changes and in some other cases. But your data belong to the Model part. They must survive the orientation change. So they must not be owned by an Activity.
To answer
a. HashMap will no doubt win over sqlite in terms of memory operations, hence it will run faster. But it will not provide you consistency, Mobile being a volatile environment, OS is bound to kill an application in background, or in foreground if its memory requirement are not met, in such scenarios you might loose all the important updates made before committing it to a permanent storage.
b. SQLITE is slow compared to Map, but is reliable it will make sure all the commits to your data is saved properly, even though app crashes db will guarantee to restore data you committed before that, Map certainly lacks this functionality.
c. Considering a Scenario when you have loaded data into a MAP to enable faster operation and performing sync with database whenever you record any delta to your data, this scenario is very plausible and can perform excellently if designed properly.
To conclude, You should proceed with DB + MAp operation, this will make your app running smooth if there is lots of database operation involved, just need to make sure keep data + app seperate to eleborate dont make your app dependant on loading of data initially.

Categories

Resources