Simple caching Java application step by step

Problem Statement: How would you go about writing an application in Java where employee id to department name lookup is cached instead of reading from a database or an API. The cache needs to be refreshed every 1 minute.

Solution, step by step

Step 1: Firstly, a simplified config class that reads config values from a “.properties” or a “.yml” file.

AppConfig.java:

Step 2: The Data Access Object to read the data from an API or a database.

Firstly, the interface EmployeeDao.java:

Next, the implementation of the interface EmployeeDaoImpl.java:

Step 3: Now the caching class that initially loads the data when it is constructed in the main thread, and then refreshes the data every X minutes in a separate scheduled thread.

The interface EmployeeCacheManager.java

The implementation class EmployeeCacheManagerImpl.java:

Step 4: Finally, the main application that can can be executed on the man thread.

Outputs:

Let it run for 5 minutes & then exit.


300+ Java Interview FAQs

Tutorials on Java & Big Data