An in-memory repository before the database
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's services need data today, but the MySQL database arrives only in the last module. To build and test them now, the rows need a home that a database can replace later without touching the service.
A repository interface: findById, findAll, save, deleteById
A repository interface lists the storage operations a feature needs (find, save, delete) without saying how they are done. The service depends on the interface, never on a class.
Here is a CategoryRepository interface with four methods, then a program that runs them.
interface CategoryRepository { Optional<Category> findById(Long id); List<Category> findAll(); Category save(Category category); // no id: insert with a new id; with an id: replace void deleteById(Long id); // a missing id is not an error}Example 1 · The four repository methods in action
import java.util.Comparator;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
class Category { private Long id; private final String name;
Category(Long id, String name) { this.id = id; this.name = name; }
Long getId() { return id; } void setId(Long id) { this.id = id; } String getName() { return name; }
@Override public String toString() { return id + ":" + name; }}
interface CategoryRepository { Optional<Category> findById(Long id);
List<Category> findAll();
Category save(Category category); // no id: insert with a new id; with an id: replace
void deleteById(Long id);}
class InMemoryCategoryRepository implements CategoryRepository { private final Map<Long, Category> rows = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(1);
public Optional<Category> findById(Long id) { return Optional.ofNullable(rows.get(id)); }
public List<Category> findAll() { return rows.values().stream().sorted(Comparator.comparing(Category::getId)).toList(); }
public Category save(Category category) { if (category.getId() == null) { category.setId(nextId.getAndIncrement()); } rows.put(category.getId(), category); return category; }
public void deleteById(Long id) { rows.remove(id); }}
public class RepositoryContractDemo { public static void main(String[] args) { CategoryRepository repository = new InMemoryCategoryRepository(); repository.save(new Category(null, "Electronics")); repository.save(new Category(null, "Books")); Category fashion = repository.save(new Category(null, "Fashion")); System.out.println("saved Fashion with id " + fashion.getId()); System.out.println("all: " + repository.findAll());
repository.save(new Category(2L, "Books & Stationery")); // same id: replaces System.out.println("after replace: " + repository.findAll());
System.out.println("find 3: " + repository.findById(3L)); repository.deleteById(3L); System.out.println("find 3 after delete: " + repository.findById(3L)); repository.deleteById(99L); // nothing there: no error System.out.println("all: " + repository.findAll()); }}saved Fashion with id 3 all: [1:Electronics, 2:Books, 3:Fashion] after replace: [1:Electronics, 2:Books & Stationery, 3:Fashion] find 3: Optional[3:Fashion] find 3 after delete: Optional.empty all: [1:Electronics, 2:Books & Stationery]
What this code does
savegives new rows the ids 1, 2 and 3. Saving a category that already has id 2 replaces that row, so Books becomes Books & Stationery.findById(3L)returnsOptional[3:Fashion]before the delete andOptional.emptyafter it. Deleting id 99, which does not exist, does nothing.findAllsorts by id, so the order never depends on the map's internal order.
Four methods cover most needs, and they follow the same rules as Spring Data, which the JPA section uses. findById returns an Optional because the row may not exist, save inserts a row that has no id yet (and gives it one) or replaces the row with that id, and deleteById with a missing id is not an error.
The service depends on the interface, never on a class. That one choice is what makes the next three sections possible.
Trace the code
Insert, replace and delete rows
Variables
- rows
- {}
Output
(nothing printed yet)Line 6The map is empty: no rows stored yet.
InMemoryProductRepository with ConcurrentHashMap and AtomicLong
A ConcurrentHashMap is a map that many threads can read and change at the same time without breaking it. ShopLite's in-memory repository keeps its rows in one.
Here is InMemoryProductRepository: rows in a map, ids from a counter, and copies going in and out.
Example 2 · src/main/java/com/shoplite/product/InMemoryProductRepository.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import java.util.Comparator;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;import java.util.stream.Stream;
import org.springframework.stereotype.Repository;
/** * Keeps products in a thread-safe map until the MySQL module replaces it with a JdbcClient repository. * It stores and returns copies, like a database: changing a returned object changes nothing until save. */@Repositoryclass InMemoryProductRepository implements ProductRepository {
private final Map<Long, Product> rows = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(1);
@Override public Optional<Product> findById(Long id) { return Optional.ofNullable(rows.get(id)).map(Product::copy); }
@Override public Optional<Product> findBySku(String sku) { return rows.values().stream() .filter(p -> p.getSku().equals(sku)) .findFirst() .map(Product::copy); }
@Override public List<Product> findAll() { return byId(rows.values().stream()).toList(); }
@Override public List<Product> findPage(ProductFilter filter, int offset, int limit) { return byId(matching(filter)).skip(offset).limit(limit).toList(); }
@Override public long count(ProductFilter filter) { return matching(filter).count(); }
@Override public boolean existsById(Long id) { return rows.containsKey(id); }
@Override public Product save(Product product) { Product row = product.copy(); if (row.getId() == null) { row.setId(nextId.getAndIncrement()); } rows.put(row.getId(), row); return row.copy(); }
@Override public void deleteById(Long id) { rows.remove(id); }
private Stream<Product> matching(ProductFilter f) { return rows.values().stream() .filter(p -> f.includeInactive() || p.isActive()) .filter(p -> f.categoryId() == null || f.categoryId().equals(p.getCategoryId())) .filter(p -> f.minPrice() == null || p.getPrice().compareTo(f.minPrice()) >= 0) .filter(p -> f.maxPrice() == null || p.getPrice().compareTo(f.maxPrice()) <= 0) .filter(p -> !f.inStockOnly() || p.getStock() > 0) .filter(p -> f.q() == null || contains(p.getName(), f.q()) || contains(p.getSku(), f.q())); }
private static boolean contains(String text, String part) { return text.toLowerCase(Locale.ROOT).contains(part.toLowerCase(Locale.ROOT)); }
private static Stream<Product> byId(Stream<Product> products) { return products.sorted(Comparator.comparing(Product::getId)).map(Product::copy); }}$ curl 'http://localhost:8080/api/v1/products?categoryId=2&maxPrice=20000'
{"content":[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true},{"id":2,"sku":"MOB-GM35","name":"Samsung Galaxy M35","categoryId":2,"categoryName":"Mobiles","price":19999.00,"stock":25,"isActive":true}],"page":0,"size":20,"totalElements":2,"totalPages":1}What this code does
savecopies the product, gives itnextId.getAndIncrement()if it has no id, stores the copy and returns another copy.findByIdand every list method also hand out copies.matchingapplies each filter only when it is set (nullorfalsemeans no filter). The call shows categoryId 2 with maxPrice 20000: two phones match, the iPhone at 69900.00 does not.- Results are sorted by id before
skipandlimit, so pages never overlap, as the contract requires.
Ids come from an AtomicLong, a counter whose getAndIncrement() is one indivisible step. The repository stores and returns copies, as a database does: a row you loaded is your own object, and changing it changes nothing until you call save. Without copies, a service that changed a loaded product and then refused the change would already have changed the stored one.
The filter methods (findPage, count) use streams over the map's values. The MySQL version later turns the same ProductFilter into a WHERE clause.
@Repository marks the class as a bean, like @Component. The class is package-private: only ProductService, in the same package, ever sees it.Why thread safety matters in a singleton repository
A singleton bean is a Spring bean of which the whole application shares one object. It is the default, so every request thread uses the same repository object.
Here eight threads save products into one shared repository, first with a plain HashMap and long, then with the concurrent versions.
Example 3 · HashMap and long vs ConcurrentHashMap and AtomicLong
import java.util.HashMap;import java.util.Map;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;
interface SkuRepository { long save(String sku);
int count();}
// Not thread-safe: a plain HashMap and a plain long counterclass UnsafeSkuRepository implements SkuRepository { private final Map<Long, String> rows = new HashMap<>(); private long nextId = 1;
public long save(String sku) { long id = nextId++; // read, add 1, write back: two threads can get the same id rows.put(id, sku); return id; }
public int count() { return rows.size(); }}
// Thread-safe: ConcurrentHashMap and AtomicLongclass SafeSkuRepository implements SkuRepository { private final Map<Long, String> rows = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(1);
public long save(String sku) { long id = nextId.getAndIncrement(); rows.put(id, sku); return id; }
public int count() { return rows.size(); }}
public class SharedRepositoryRaceDemo { static int saveFromManyThreads(SkuRepository repository) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(8); for (int t = 0; t < 8; t++) { int thread = t; pool.submit(() -> { for (int i = 0; i < 10_000; i++) { repository.save("SKU-" + thread + "-" + i); } }); } pool.shutdown(); pool.awaitTermination(1, TimeUnit.MINUTES); return repository.count(); }
public static void main(String[] args) throws InterruptedException { System.out.println("Products saved: 80000"); System.out.println("Unsafe repository holds: " + saveFromManyThreads(new UnsafeSkuRepository())); System.out.println("Safe repository holds: " + saveFromManyThreads(new SafeSkuRepository())); }}Products saved: 80000 Unsafe repository holds: 65551 Safe repository holds: 80000
What this code does
- Eight threads each save 10,000 products into one shared repository, like eight request threads using one singleton bean.
- The unsafe version loses a few thousand rows: duplicate ids overwrite each other, and the
HashMapdrops entries. The number changes on every run. - The safe version always holds 80000, because every
getAndIncrement()gives a different id and everyputis safe.
Tomcat serves requests on many threads at once, so two buyers can call save on the same repository object at the same moment. With a plain HashMap and nextId++, two threads can read the same counter value and get the same id, and a HashMap changed by two threads at once can lose entries or break inside. Nothing crashes; rows simply go missing, and only under load.
ConcurrentHashMap and AtomicLong make each single operation safe. They do not make a check-then-act pair safe: two requests can both see that a SKU is free and both save it. The MySQL module fixes that with a UNIQUE constraint, as the API contract says.
Swapping to a JDBC implementation later without touching the service
Here is one ProductService running on two repository implementations, then the failure when both are beans at once.
Example 4 · One service, two repository implementations
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
record Product(Long id, String sku, BigDecimal price) {}
interface ProductRepository { Optional<Product> findBySku(String sku);
Product save(Product product);
List<Product> findAll();}
// Implementation 1: a map, like ShopLite's InMemoryProductRepositoryclass MapProductRepository implements ProductRepository { private final Map<Long, Product> rows = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(1);
public Optional<Product> findBySku(String sku) { return rows.values().stream().filter(p -> p.sku().equals(sku)).findFirst(); }
public Product save(Product product) { Product row = new Product(nextId.getAndIncrement(), product.sku(), product.price()); rows.put(row.id(), row); return row; }
public List<Product> findAll() { return rows.values().stream().sorted((a, b) -> Long.compare(a.id(), b.id())).toList(); }}
// Implementation 2: a different storage idea (a list that also logs), same contractclass LoggingListProductRepository implements ProductRepository { private final List<Product> rows = new ArrayList<>();
public synchronized Optional<Product> findBySku(String sku) { System.out.println(" (list) scan for " + sku); return rows.stream().filter(p -> p.sku().equals(sku)).findFirst(); }
public synchronized Product save(Product product) { Product row = new Product((long) rows.size() + 1, product.sku(), product.price()); rows.add(row); System.out.println(" (list) append " + row.sku()); return row; }
public synchronized List<Product> findAll() { return List.copyOf(rows); }}
// The service never names an implementation: only the interfaceclass ProductService { private final ProductRepository repository;
ProductService(ProductRepository repository) { this.repository = repository; }
String add(String sku, String price) { if (repository.findBySku(sku).isPresent()) { return "409 " + sku + " already exists"; } return "201 id " + repository.save(new Product(null, sku, new BigDecimal(price))).id(); }}
public class SwapRepositoryDemo { static void run(String label, ProductRepository repository) { System.out.println(label); ProductService service = new ProductService(repository); System.out.println(service.add("BK-CLEAN", "499.00")); System.out.println(service.add("BK-PRAG", "650.00")); System.out.println(service.add("BK-CLEAN", "549.00")); System.out.println("stored: " + repository.findAll().size()); }
public static void main(String[] args) { run("With MapProductRepository:", new MapProductRepository()); run("With LoggingListProductRepository:", new LoggingListProductRepository()); }}With MapProductRepository: 201 id 1 201 id 2 409 BK-CLEAN already exists stored: 2 With LoggingListProductRepository: (list) scan for BK-CLEAN (list) append BK-CLEAN 201 id 1 (list) scan for BK-PRAG (list) append BK-PRAG 201 id 2 (list) scan for BK-CLEAN 409 BK-CLEAN already exists stored: 2
What this code does
ProductServicenames only theProductRepositoryinterface, so the same service code runs on top of both classes.- The answers are identical; only the storage differs, which the logging version makes visible. A JDBC version later is just a third implementation.
Example 5 · Two repository beans at once: the startup failure
Runs in: a copy of the shoplite-api project with a second @Repository class
// src/main/java/com/shoplite/product/JdbcProductRepository.java (started too early)package com.shoplite.product;
import java.util.List;import java.util.Optional;
import org.springframework.stereotype.Repository;
// Started too early: the MySQL version, added while the in-memory one is still a bean@Repositoryclass JdbcProductRepository implements ProductRepository {
@Override public Optional<Product> findById(Long id) { throw new UnsupportedOperationException("not written yet"); }
@Override public Optional<Product> findBySku(String sku) { throw new UnsupportedOperationException("not written yet"); }
@Override public List<Product> findAll() { throw new UnsupportedOperationException("not written yet"); }
@Override public List<Product> findPage(ProductFilter filter, int offset, int limit) { throw new UnsupportedOperationException("not written yet"); }
@Override public long count(ProductFilter filter) { throw new UnsupportedOperationException("not written yet"); }
@Override public boolean existsById(Long id) { throw new UnsupportedOperationException("not written yet"); }
@Override public Product save(Product product) { throw new UnsupportedOperationException("not written yet"); }
@Override public void deleteById(Long id) { throw new UnsupportedOperationException("not written yet"); }}*************************** APPLICATION FAILED TO START *************************** Description: Parameter 0 of constructor in com.shoplite.product.ProductService required a single bean, but 2 were found: - inMemoryProductRepository: defined in file [...\shoplite-api\target\classes\com\shoplite\product\InMemoryProductRepository.class] - jdbcProductRepository: defined in file [...\shoplite-api\target\classes\com\shoplite\product\JdbcProductRepository.class] This may be due to missing parameter name information Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed Ensure that your compiler is configured to use the '-parameters' flag. You may need to update both your build tool settings as well as your IDE. (See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-6.1-Release-Notes#parameter-name-retention)
What this code does
- Both
InMemoryProductRepositoryand this class are@Repositorybeans that implementProductRepository, so Spring cannot choose one forProductService's constructor. - The "missing parameter name" hint is general advice; Spring Boot's parent already compiles with
-parameters. The real fix here: the new class replaces the old one, so deleteInMemoryProductRepositoryin the same change. - The paths are shortened with
...; yours show your own project folder.
Because ProductService asks for a ProductRepository, any class that implements the interface can stand behind it. In the last module of this section, JdbcProductRepository runs SQL with JdbcClient; you delete InMemoryProductRepository, and the service, the controller and their tests stay as they are.
The swap must be a swap. If both classes are beans at once, Spring finds two candidates for one constructor parameter and refuses to start, as the report above shows. Remove the old class (or stop it being a bean) in the same change that adds the new one.
@Primary and @Qualifier (see the Several implementations lesson). They are right when you really need two implementations; for a replacement, just delete the old one.Fake repositories make fast service unit tests
A fake is a small, working implementation of an interface, used only in tests. An in-memory repository makes a good fake: it needs no database, and a test can look inside it afterwards.
Here is ProductServiceTest: it builds the service with a fresh in-memory repository and checks the rules.
Example 6 · src/test/java/com/shoplite/product/ProductServiceTest.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.ArgumentMatchers.anyCollection;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;
import com.shoplite.category.CategoryService;import com.shoplite.common.BusinessRuleException;import com.shoplite.common.ConflictException;import com.shoplite.common.NotFoundException;import com.shoplite.common.PageResponse;
class ProductServiceTest {
private InMemoryProductRepository repository; // a real, fast fake: no Spring, no database private ProductService service;
@BeforeEach void setUp() { CategoryService categories = mock(CategoryService.class); when(categories.findName(2L)).thenReturn(Optional.of("Mobiles")); when(categories.findName(4L)).thenReturn(Optional.of("Accessories")); when(categories.findName(42L)).thenReturn(Optional.empty()); when(categories.findNames(anyCollection())).thenReturn(Map.of(2L, "Mobiles", 4L, "Accessories"));
repository = new InMemoryProductRepository(); service = new ProductService(repository, categories); service.create(request("MOB-RN13", 2, "17999", 40)); service.create(request("MOB-IP15", 2, "69900", 8)); service.create(request("ACC-AD141", 4, "1299", 0)); }
@Test void createGivesTheNextIdTwoDecimalPriceAndCategoryName() { ProductResponse created = service.create(request("ACC-KB100", 4, "999", null));
assertThat(created.id()).isEqualTo(4L); assertThat(created.price()).isEqualByComparingTo("999.00"); assertThat(created.price().scale()).isEqualTo(2); assertThat(created.categoryName()).isEqualTo("Accessories"); assertThat(created.stock()).isZero(); assertThat(created.isActive()).isTrue(); }
@Test void createRefusesUnknownCategoryAndSavesNothing() { assertThatThrownBy(() -> service.create(request("ACC-KB100", 42, "999", 30))) .isInstanceOf(BusinessRuleException.class) .hasMessage("Category 42 does not exist."); assertThat(repository.findAll()).hasSize(3); }
@Test void createRefusesDuplicateSku() { assertThatThrownBy(() -> service.create(request("MOB-RN13", 2, "999", 30))) .isInstanceOf(ConflictException.class) .hasMessage("A product with SKU MOB-RN13 already exists."); }
@Test void replaceMayKeepItsOwnSku() { ProductResponse updated = service.replace(1L, new UpdateProductRequest("MOB-RN13", "Redmi Note 13 5G (8GB)", 2L, new BigDecimal("18999"), 35, true));
assertThat(updated.name()).isEqualTo("Redmi Note 13 5G (8GB)"); assertThat(updated.price()).isEqualByComparingTo("18999.00"); }
@Test void getAndDeleteUnknownIdThrowNotFound() { assertThatThrownBy(() -> service.get(99L)) .isInstanceOf(NotFoundException.class) .hasMessage("Product 99 was not found."); assertThatThrownBy(() -> service.delete(99L)).isInstanceOf(NotFoundException.class); }
@Test void searchFiltersByCategoryAndPriceAndPages() { ProductFilter mobilesUnder20k = new ProductFilter(null, 2L, null, new BigDecimal("20000"), false, false);
PageResponse<ProductResponse> page = service.search(mobilesUnder20k, 0, 20);
assertThat(page.content()).extracting(ProductResponse::sku).containsExactly("MOB-RN13"); assertThat(page.totalElements()).isEqualTo(1);
PageResponse<ProductResponse> second = service.search(ProductFilter.none(), 1, 2); assertThat(second.content()).extracting(ProductResponse::id).containsExactly(3L); assertThat(second.totalPages()).isEqualTo(2); }
@Test void changingAReturnedObjectDoesNotChangeTheStore() { Product loaded = repository.findById(1L).orElseThrow(); loaded.setStock(0);
assertThat(repository.findById(1L).orElseThrow().getStock()).isEqualTo(40); }
private static CreateProductRequest request(String sku, long categoryId, String price, Integer stock) { return new CreateProductRequest(sku, "Product " + sku, categoryId, new BigDecimal(price), stock, null); }}$ mvn test -Dtest=ProductServiceTest ... [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.shoplite.product.ProductServiceTest [INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.934 s -- in com.shoplite.product.ProductServiceTest [INFO] Results: [INFO] Tests run: 7, Failures: 0, Errors: 0, Skipped: 0 [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS
What this code does
- The test is in the same package as the service, so it may use the package-private
ProductServiceconstructor andInMemoryProductRepository. A fresh repository is built before every test, so tests never see each other's rows. - The tests check outcomes, not steps: the new id is 4,
999became999.00, a refused create left 3 rows, and a changed copy did not change the store. - Most of the 2.9 seconds is the JVM and Mockito starting; the seven tests themselves take milliseconds. Your timing will differ.
A unit test checks one class on its own. ProductServiceTest creates the service with new, so no Spring context starts and all seven tests take well under a second once the JVM is warm.
The category feature is replaced by a Mockito mock (mock, when, as with @MockitoBean in the REST Controllers module): a stand-in programmed with fixed answers, handy for another feature's service.
Next step
Check your understanding
12 quick questions