Skip to content

Commit

Permalink
fix: Version number pattern update overwritten #2968 (#2980)
Browse files Browse the repository at this point in the history
* Fix bug #2968

* Fix bug #2968
  • Loading branch information
Avinash2110 authored Jun 2, 2024
1 parent d4b0f3d commit dd38bd3
Showing 1 changed file with 17 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -34,7 +33,8 @@
* as much as in real databases.
*/
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.
Expand All @@ -57,19 +57,22 @@ public void update(Book book) throws BookNotFoundException, VersionMismatchExcep
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);
// 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));
// save book copy to repository
collection.put(book.getId(), new Book(book));
}
}

/**
Expand Down

0 comments on commit dd38bd3

Please sign in to comment.