Junior
Does caching work only with databases?
sobes.tech AI
Answer from AI
No, caching is applied to any data or computation results that are frequently requested and relatively static. It is used to speed up access to this data by storing it in faster memory or storage than the original source. Besides databases, caching is widely used in the following areas:
- Web servers: For storing static resources (HTML, CSS, JavaScript, images) and results of dynamic requests.
- Applications: For caching results of expensive computations, configuration data, user sessions.
- Operating systems: For caching frequently used files and data in RAM (file system cache).
- DNS servers: For caching IP addresses corresponding to domain names.
- CDN (Content Delivery Network): For distributing copies of content to geographically distributed servers and providing them to users from the nearest server.
Examples in Java:
-
Using
HashMapfor caching function results:// Cache for function results private Map<Integer, String> cache = new HashMap<>(); public String expensiveComputation(int input) { // Check if result is in cache if (cache.containsKey(input)) { return cache.get(input); // Return cached result } // Perform expensive computation String result = "Computed_result_for_" + input; // Simulate computation // Store result in cache cache.put(input, result); return result; } -
Using
@Cacheablefrom Spring Cache:import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class DataService { @Cacheable("items") // Cache results of this method under "items" cache name public Item getItemById(Long id) { // Simulate fetching data from a slow source (e.g., external service) System.out.println("Fetching item from source: " + id); try { Thread.sleep(1000); // Simulate delay } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return new Item(id, "Item " + id); } } -
Using Ehcache or Caffeine as caching libraries for more complex scenarios with eviction policies, distributed caching, etc.