|
| 1 | +--- |
| 2 | +layout: pattern |
| 3 | +title: Version Number |
| 4 | +folder: versionnumber |
| 5 | +permalink: /patterns/versionnumber/ |
| 6 | +description: Entity versioning with version number |
| 7 | + |
| 8 | +categories: |
| 9 | + - Concurrency |
| 10 | + |
| 11 | +tags: |
| 12 | + - Data access |
| 13 | + - Microservices |
| 14 | +--- |
| 15 | + |
| 16 | +## Name / classification |
| 17 | + |
| 18 | +Version Number. |
| 19 | + |
| 20 | +## Also known as |
| 21 | + |
| 22 | +Entity Versioning, Optimistic Locking. |
| 23 | + |
| 24 | +## Intent |
| 25 | + |
| 26 | +Resolve concurrency conflicts when multiple clients are trying to update same entity simultaneously. |
| 27 | + |
| 28 | +## Explanation |
| 29 | + |
| 30 | +Real world example |
| 31 | + |
| 32 | +> Alice and Bob are working on the book, which stored in the database. Our heroes are making |
| 33 | +> changes simultaneously, and we need some mechanism to prevent them from overwriting each other. |
| 34 | +
|
| 35 | +In plain words |
| 36 | + |
| 37 | +> Version Number pattern grants protection against concurrent updates to same entity. |
| 38 | +
|
| 39 | +Wikipedia says |
| 40 | + |
| 41 | +> Optimistic concurrency control assumes that multiple transactions can frequently complete |
| 42 | +> without interfering with each other. While running, transactions use data resources without |
| 43 | +> acquiring locks on those resources. Before committing, each transaction verifies that no other |
| 44 | +> transaction has modified the data it has read. If the check reveals conflicting modifications, |
| 45 | +> the committing transaction rolls back and can be restarted. |
| 46 | +
|
| 47 | +**Programmatic Example** |
| 48 | + |
| 49 | +We have a `Book` entity, which is versioned, and has a copy-constructor: |
| 50 | + |
| 51 | +```java |
| 52 | +public class Book { |
| 53 | + private long id; |
| 54 | + private String title = ""; |
| 55 | + private String author = ""; |
| 56 | + |
| 57 | + private long version = 0; // version number |
| 58 | + |
| 59 | + public Book(Book book) { |
| 60 | + this.id = book.id; |
| 61 | + this.title = book.title; |
| 62 | + this.author = book.author; |
| 63 | + this.version = book.version; |
| 64 | + } |
| 65 | + |
| 66 | + // getters and setters are omitted here |
| 67 | +} |
| 68 | +``` |
| 69 | + |
| 70 | +We also have `BookRepository`, which implements concurrency control: |
| 71 | + |
| 72 | +```java |
| 73 | +public class BookRepository { |
| 74 | + private final Map<Long, Book> collection = new HashMap<>(); |
| 75 | + |
| 76 | + public void update(Book book) throws BookNotFoundException, VersionMismatchException { |
| 77 | + if (!collection.containsKey(book.getId())) { |
| 78 | + throw new BookNotFoundException("Not found book with id: " + book.getId()); |
| 79 | + } |
| 80 | + |
| 81 | + var latestBook = collection.get(book.getId()); |
| 82 | + if (book.getVersion() != latestBook.getVersion()) { |
| 83 | + throw new VersionMismatchException( |
| 84 | + "Tried to update stale version " + book.getVersion() |
| 85 | + + " while actual version is " + latestBook.getVersion() |
| 86 | + ); |
| 87 | + } |
| 88 | + |
| 89 | + // update version, including client representation - modify by reference here |
| 90 | + book.setVersion(book.getVersion() + 1); |
| 91 | + |
| 92 | + // save book copy to repository |
| 93 | + collection.put(book.getId(), new Book(book)); |
| 94 | + } |
| 95 | + |
| 96 | + public Book get(long bookId) throws BookNotFoundException { |
| 97 | + if (!collection.containsKey(bookId)) { |
| 98 | + throw new BookNotFoundException("Not found book with id: " + bookId); |
| 99 | + } |
| 100 | + |
| 101 | + // return copy of the book |
| 102 | + return new Book(collection.get(bookId)); |
| 103 | + } |
| 104 | +} |
| 105 | +``` |
| 106 | + |
| 107 | +Here's the concurrency control in action: |
| 108 | + |
| 109 | +```java |
| 110 | +var bookId = 1; |
| 111 | +// Alice and Bob took the book concurrently |
| 112 | +final var aliceBook = bookRepository.get(bookId); |
| 113 | +final var bobBook = bookRepository.get(bookId); |
| 114 | + |
| 115 | +aliceBook.setTitle("Kama Sutra"); // Alice has updated book title |
| 116 | +bookRepository.update(aliceBook); // and successfully saved book in database |
| 117 | +LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion()); |
| 118 | + |
| 119 | +// now Bob has the stale version of the book with empty title and version = 0 |
| 120 | +// while actual book in database has filled title and version = 1 |
| 121 | +bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author |
| 122 | +try { |
| 123 | + LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion()); |
| 124 | + bookRepository.update(bobBook); // Bob tries to save his book to database |
| 125 | +} catch (VersionMismatchException e) { |
| 126 | + // Bob update fails, and book in repository remained untouchable |
| 127 | + LOGGER.info("Exception: {}", e.getMessage()); |
| 128 | + // Now Bob should reread actual book from repository, do his changes again and save again |
| 129 | +} |
| 130 | +``` |
| 131 | + |
| 132 | +Program output: |
| 133 | + |
| 134 | +```java |
| 135 | +Alice updates the book with new version 1 |
| 136 | +Bob tries to update the book with his version 0 |
| 137 | +Exception: Tried to update stale version 0 while actual version is 1 |
| 138 | +``` |
| 139 | + |
| 140 | +## Class diagram |
| 141 | + |
| 142 | + |
| 143 | + |
| 144 | +## Applicability |
| 145 | + |
| 146 | +Use Version Number for: |
| 147 | + |
| 148 | +* resolving concurrent write-access to the data |
| 149 | +* strong data consistency |
| 150 | + |
| 151 | +## Tutorials |
| 152 | +* [Version Number Pattern Tutorial](http://www.java2s.com/Tutorial/Java/0355__JPA/VersioningEntity.htm) |
| 153 | + |
| 154 | +## Known uses |
| 155 | + * [Hibernate](https://vladmihalcea.com/jpa-entity-version-property-hibernate/) |
| 156 | + * [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning) |
| 157 | + * [Apache Solr](https://lucene.apache.org/solr/guide/6_6/updating-parts-of-documents.html) |
| 158 | + |
| 159 | +## Consequences |
| 160 | +Version Number pattern allows to implement a concurrency control, which is usually done |
| 161 | +via Optimistic Offline Lock pattern. |
| 162 | + |
| 163 | +## Related patterns |
| 164 | +* [Optimistic Offline Lock](https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html) |
| 165 | + |
| 166 | +## Credits |
| 167 | +* [Optimistic Locking in JPA](https://www.baeldung.com/jpa-optimistic-locking) |
| 168 | +* [JPA entity versioning](https://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking) |
| 169 | +* [J2EE Design Patterns](http://ommolketab.ir/aaf-lib/axkwht7wxrhvgs2aqkxse8hihyu9zv.pdf) |
0 commit comments