Java 17 Recipes
-8. Creating Thread-Safe Objects
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
10-8. Creating Thread-Safe Objects
Problem You need to create a thread-safe object that is accessed from multiple threads. Chapter 10 ConCurrenCy 384 Solution 1 Use synchronized getters and setters and protect critical regions that change state. In the following example, an object is created with getters and setters that are synchronized for each internal variable. The critical regions are protected by using the synchronized(this) lock. public class CustomerOrder { private String itemOrdered; private int quantityOrdered; private String customerName; public CustomerOrder() { } public double calculateOrderTotal (double price) { synchronized (this) { return getQuantityOrdered()*price; } } public synchronized String getItemOrdered() { return itemOrdered; } public synchronized int getQuantityOrdered() { return quantityOrdered; } public synchronized String getCustomerName() { return customerName; } public synchronized void setItemOrdered(String itemOrdered) { this.itemOrdered = itemOrdered; } public synchronized void setQuantityOrdered(int quantityOrdered) { this.quantityOrdered = quantityOrdered; } Chapter 10 ConCurrenCy 385 public synchronized void setCustomerName(String customerName) { this.customerName = customerName; } } Solution 2 Create an immutable object (an object that, once created, doesn’t change its internal state). In the following code, the object’s internal variables are declared final and are assigned at construction. By doing so, it is guaranteed that the object is immutable. public class ImmutableCustomerOrder { final private String itemOrdered; final private int quantityOrdered; final private String customerName; ImmutableCustomerOrder(String itemOrdered, int quantityOrdered, String customerName) { this.itemOrdered = itemOrdered; this.quantityOrdered = quantityOrdered; this.customerName = customerName; } public String getItemOrdered() { return itemOrdered; } public int getQuantityOrdered() { return quantityOrdered; } public String getCustomerName() { return customerName; } public double calculateOrderTotal (double price) { return getQuantityOrdered()*price; } } Chapter 10 ConCurrenCy |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling