Different threads updating different attribute of the same object, will it work?

91 views Asked by At

I have one method as follows:

public Book enrichBook(Book book) {
  Long bookId = book.getId();

  Thread t1 = new Thread(() -> book.setAuthors(authorService.findByBookId(bookId)));
  Thread t2 = new Thread(() -> book.setPrice(priceService.calcByBookId(bookId)));
  t1.start(); t2.start();
  
  t1.join(); t2.join();
  return book;
}

(Note : My book object is just simply object without volatile or synchronized keyword on it)

From a main thread, two threads were created to update different attributes of an object. Thread t1 updates author attribute, thread t2 updates price attribute.

I have debugged many times and it works correctly without any problem, but is there any scenario where this code can break or cause strange behavior? For example the final result will only have the updating of one attribute.

My other approach is to use CompletableFutures, does it has the same behavior like the first one when use thread?

public Book enrichBook(Book book) {
  Long bookId = book.getId();

  CompletableFuture<Void> authorFuture = CompletableFuture.runAsync(()->  book.setAuthors(authorService.findByBookId(bookId)), appConfig.getAsyncExecutor());
  CompletableFuture<Void> priceFuture = CompletableFuture.runAsync(()-> book.setPrice(priceService.calcByBookId(bookId)), appConfig.getAsyncExecutor());
  
  List<CompletableFuture<Void>> completableFutures = new ArrayList<>();
  completableFutures.add(authorFuture); 
  completableFutures.add(priceFuture);
  
  CompletableFuture<Void> allFuturesResult = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]));
  allFuturesResult.join(); // try - catch is igored here
  
  return book;
}

Will this work or will there be unexpected results?

1

There are 1 answers

2
Hamzeh On

Exclusively changing different plain attributes of an object by different threads has no problem. Of course you cannot be sure about orders of changes per execution.