2

I have a situation where i have to run a method once only for one empID. Let me explain code wise.

                oldDataObject =  converter.retrieveByID(EmpID);

The above line of code runs in one class and being called from other java class. I want a filter that id EmpID is passed same , donot run this method and just return the previously processed and retreived DataObject. I tested my code and this method is called 5 times with same EmpID and firing huge DB statements each time to fetch the same object. I was looking to improve the performance. Can you please tell me to run this code once per ID and store the value and compare the ID next time its called and skips if it is same ID and return the already retrieved object. Please help

Jimmy_R
  • 21
  • 4
  • 2
    Use either static fields or Singleton Pattern. The easiest approach would be to create static HashMap where you keep objects (ID, DataObject). If object is there, get it from HashMap, if not, get from DB and store inside HashMap. – Oo.oO Jul 12 '17 at 17:39
  • There are more than 10,000 empId's , storing in map and then retrieving , is it the best we can do ? – Jimmy_R Jul 12 '17 at 17:44
  • You can use BerkeleyDB as your backend: http://www.oracle.com/technetwork/database/database-technologies/berkeleydb/overview/index.html This way, you can keep data close to your code once they are retrieved from DB. – Oo.oO Jul 12 '17 at 17:51
  • Please read [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions. –  Jul 12 '17 at 17:51
  • Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions. –  Jul 12 '17 at 17:51
  • There are different memory `cache` systems available to eliminate redundant calls to DB such as Hibernate. You can search the Internet for different Java caching examples. – MaxZoom Jul 12 '17 at 17:53
  • **Stop posting duplicate questions just because you are not getting answers as quickly as you want or the answer you want.** Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) before attempting to ask more questions. –  Jul 12 '17 at 17:57

1 Answers1

0
oldDataObject = cache.get( EmpID );
if( oldDataObject == null ) {
   oldDataObject = converter.retrieveByID(EmpID);
   cache.put( EmpID, oldDataObject );
}
return oldDataObject;

You have to define cache as attribute of type Map<K, V> with K the type of EmpID and V the type of oldDataObject.

If you do so, you have a new problem: when to invalidate cache?

You may use a timeout...

Aubin
  • 14,617
  • 9
  • 61
  • 84