fix: Version number pattern update overwritten #2968 (#2980)

* Fix bug #2968

* Fix bug #2968
This commit is contained in:
Avinash Shukla authored and GitHub committed 2024-06-02 16:53:15 +03:00
1 parent d4b0f3db8d
commit dd38bd3ffb
1 file changed
+18 -15
@@ -24,8 +24,7 @@
*/ */
package com.iluwatar.versionnumber; package com.iluwatar.versionnumber;
import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;
/** /**
* This repository represents simplified database. * This repository represents simplified database.
@@ -34,7 +33,8 @@ import java.util.Map;
* as much as in real databases. * as much as in real databases.
*/ */
public class BookRepository { public class BookRepository {
private final Map<Long, Book> collection = new HashMap<>(); private final ConcurrentHashMap<Long, Book> collection = new ConcurrentHashMap<>();
private final Object lock = new Object();
/** /**
* Adds book to collection. * Adds book to collection.
@@ -57,19 +57,22 @@ public class BookRepository {
throw new BookNotFoundException("Not found book with id: " + book.getId()); throw new BookNotFoundException("Not found book with id: " + book.getId());
} }
var latestBook = collection.get(book.getId()); // used synchronized block to ensure only one thread compares and update the version
if (book.getVersion() != latestBook.getVersion()) { synchronized (lock) {
throw new VersionMismatchException( var latestBook = collection.get(book.getId());
"Tried to update stale version " + book.getVersion() if (book.getVersion() != latestBook.getVersion()) {
+ " while actual version is " + 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));
} }
/** /**