mirror of
https://github.com/tiennm99/java-design-patterns.git
synced 2026-10-14 22:17:38 +00:00
1 parent
d4b0f3db8d
commit
dd38bd3ffb
1 file changed
+6
-3
@@ -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,6 +57,8 @@ public class BookRepository {
|
|||||||
throw new BookNotFoundException("Not found book with id: " + book.getId());
|
throw new BookNotFoundException("Not found book with id: " + book.getId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// used synchronized block to ensure only one thread compares and update the version
|
||||||
|
synchronized (lock) {
|
||||||
var latestBook = collection.get(book.getId());
|
var latestBook = collection.get(book.getId());
|
||||||
if (book.getVersion() != latestBook.getVersion()) {
|
if (book.getVersion() != latestBook.getVersion()) {
|
||||||
throw new VersionMismatchException(
|
throw new VersionMismatchException(
|
||||||
@@ -71,6 +73,7 @@ public class BookRepository {
|
|||||||
// save book copy to repository
|
// save book copy to repository
|
||||||
collection.put(book.getId(), new Book(book));
|
collection.put(book.getId(), new Book(book));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns book representation to the client.
|
* Returns book representation to the client.
|
||||||
|
|||||||
Reference in new issue
Block a user