Skip to content

Commit dd38bd3

Browse files
authored
fix: Version number pattern update overwritten #2968 (#2980)
* Fix bug #2968 * Fix bug #2968
1 parent d4b0f3d commit dd38bd3

File tree

1 file changed

+17
-14
lines changed

1 file changed

+17
-14
lines changed

version-number/src/main/java/com/iluwatar/versionnumber/BookRepository.java

Lines changed: 17 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@
2424
*/
2525
package com.iluwatar.versionnumber;
2626

27-
import java.util.HashMap;
28-
import java.util.Map;
27+
import java.util.concurrent.ConcurrentHashMap;
2928

3029
/**
3130
* This repository represents simplified database.
@@ -34,7 +33,8 @@
3433
* as much as in real databases.
3534
*/
3635
public class BookRepository {
37-
private final Map<Long, Book> collection = new HashMap<>();
36+
private final ConcurrentHashMap<Long, Book> collection = new ConcurrentHashMap<>();
37+
private final Object lock = new Object();
3838

3939
/**
4040
* Adds book to collection.
@@ -57,19 +57,22 @@ public void update(Book book) throws BookNotFoundException, VersionMismatchExcep
5757
throw new BookNotFoundException("Not found book with id: " + book.getId());
5858
}
5959

60-
var latestBook = collection.get(book.getId());
61-
if (book.getVersion() != latestBook.getVersion()) {
62-
throw new VersionMismatchException(
63-
"Tried to update stale version " + book.getVersion()
64-
+ " while actual version is " + latestBook.getVersion()
65-
);
66-
}
60+
// used synchronized block to ensure only one thread compares and update the version
61+
synchronized (lock) {
62+
var latestBook = collection.get(book.getId());
63+
if (book.getVersion() != latestBook.getVersion()) {
64+
throw new VersionMismatchException(
65+
"Tried to update stale version " + book.getVersion()
66+
+ " while actual version is " + latestBook.getVersion()
67+
);
68+
}
6769

68-
// update version, including client representation - modify by reference here
69-
book.setVersion(book.getVersion() + 1);
70+
// update version, including client representation - modify by reference here
71+
book.setVersion(book.getVersion() + 1);
7072

71-
// save book copy to repository
72-
collection.put(book.getId(), new Book(book));
73+
// save book copy to repository
74+
collection.put(book.getId(), new Book(book));
75+
}
7376
}
7477

7578
/**

0 commit comments

Comments
 (0)