2424 */
2525package 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.
3433 * as much as in real databases.
3534 */
3635public 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