Java Singleton Cache Example

Problem

Given the Java cache interface below, write a singleton class that implements the interface so that no warnings are generated without using @SuppressWarnings annotations

Solution

The question is mainly about two points:

  1. Type checking warning must be fixed
  2. Singleton design pattern should be implemented

here is how I approached the problem…

  1. I modified the map private member to accept key and value as objects
  2. Singleton design pattern can be implemented by using a private constructor so that the class can not be instantiated directly. Only one instance is kept and can be returned by a special method called getInstance

The hash map object is shared between put and get methods so it should be protected in a multithreaded environment. Synchronization primitives such as semaphores, monitors or even simple locking can take care of that. It is a separate topic in OS design but for the sake of this exercise we will be using ConcurrentHashMap. To do that just replace HashMap with ConcurrentHashMap. You also need to import java.util.concurrent.* as follows

Please use the comments section below for questions, corrections or feedback. Thanks for reading.

Tags:
2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *