has a static variable x storing some details.
I have a method setX to update it (it has some db calls).
x is accessed to get details in different user requests from different classes.
But each time it's accessed, it has to be updated by calling setX, which increases db calls and therefore response time.
I can periodically call setX in a schedule and not call setX in each request, but that means the user doesn't always get the updated values.
Or I can call setX whenever the db gets updated, but another dev could forget to call setX when he updates the db and introduce bugs.
What's the right way to design this type of construct? I believe this is a common issue that has a standard solution?
)))))) I've just answered your old question, which is related to static methods and fields too)))
Read my previous answer, it has some important notes about static data in general. Now this question. I clearly see here that you are using static when it's not needed here at all. The > x is accessed to get details in different user requests is a clear sign of that you should not make it static. Let each user create their own data, that is not shared (i.e. is in instance fields, not static), make new objects for each user. You're right, this is the common task. To understand the best practice design would be to consider several things that you didn't tought about yet: - when user receives response, does he see the *persistent* state? I.e. if the application will crash right away after user receives the response, after restart will the user see same state? This is crucial part here, as this is called "consistency", and the way how to implement things mostly depends on the consistency guarantees you want to provide. Strong consistencty is the preference, thus the most common design is to guarantee that the state is already persisted (saved to DB, file, whatever what survives app restart) when user receives response for his request. So the common flow is - receive request - fetch necessary data from DB (or from cache) - calculate stuff by your business logic - write results to DB - invalidate related cache entries - return response
Simple suggestion: get rid of static. Do not store anything "globally" or "info for all users in one single place". And everything will become much more simple after that.
(continuation) - next problem to think about - when your application won't be able to handle the load of incoming requests it would need to be scaled. How will it work when there will be 2 instances of your application running? 5 instances? 20 instances? What will happen when first request of the user will be served by instance N7 and it will crash after than, and next request from the same user will land to instance N11 ? Your approach with static methods and periodic sync calls will be a pain in the ... for this real life usecases.
Обсуждают сегодня