From dd38bd3ffb1063a271249d5d21979a332b7ba0f2 Mon Sep 17 00:00:00 2001 From: Avinash Shukla <37360069+Avinash2110@users.noreply.github.com> Date: Sun, 2 Jun 2024 19:23:15 +0530 Subject: [PATCH] fix: Version number pattern update overwritten #2968 (#2980) * Fix bug #2968 * Fix bug #2968 --- .../versionnumber/BookRepository.java | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java b/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java index fa0620222..a1baa3665 100644 --- a/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java +++ b/version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java @@ -24,8 +24,7 @@ */ package com.iluwatar.versionnumber; -import java.util.HashMap; -import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * This repository represents simplified database. @@ -34,7 +33,8 @@ import java.util.Map; * as much as in real databases. */ public class BookRepository { - private final Map collection = new HashMap<>(); + private final ConcurrentHashMap collection = new ConcurrentHashMap<>(); + private final Object lock = new Object(); /** * Adds book to collection. @@ -57,19 +57,22 @@ public class BookRepository { throw new BookNotFoundException("Not found book with id: " + book.getId()); } - var latestBook = collection.get(book.getId()); - if (book.getVersion() != latestBook.getVersion()) { - throw new VersionMismatchException( - "Tried to update stale version " + book.getVersion() - + " while actual version is " + latestBook.getVersion() - ); + // used synchronized block to ensure only one thread compares and update the version + synchronized (lock) { + var latestBook = collection.get(book.getId()); + if (book.getVersion() != latestBook.getVersion()) { + throw new VersionMismatchException( + "Tried to update stale version " + book.getVersion() + + " while actual version is " + latestBook.getVersion() + ); + } + + // update version, including client representation - modify by reference here + book.setVersion(book.getVersion() + 1); + + // save book copy to repository + collection.put(book.getId(), new Book(book)); } - - // update version, including client representation - modify by reference here - book.setVersion(book.getVersion() + 1); - - // save book copy to repository - collection.put(book.getId(), new Book(book)); } /**