Skip to content

Instantly share code, notes, and snippets.

View jgwest's full-sized avatar
🐶

Jonathan West jgwest

🐶
  • Red Hat
  • Toronto, Ontario, Canada
View GitHub Profile
class CustomerDb2 {
private final List<Customers> customers = new ArrayList<>();
private void addCustomer(Customer c) {
synchronized(customers) {
customers.add(c);
}
}
SharedThreadContext threadContext = {...}
final YourProtectedData[] ypd = new YourProtectedData[1];
threadContext.own(stc -> {
YourProtectedData innerYpd = stc.getProtectedData();
ypd[0] = innerYpd;
}, logContext);
ypd[0].incrementSomeData(); // FAILS with exception: An attempt was made (...)
SharedThreadContext stc = {...};
YourProtectedData ypd = stc.getProtectedData(); // FAILS with exception: An attempt was made to call a method in shared context without owning the required lock.
Integer someData = 10;
SharedThreadContext threadContext = new SharedThreadContext(someData);
threadContext.own(stc -> {
YourProtectedData ypd = stc.getProtectedData();
int newValue = ypd.incrementSomeData();
System.out.println("New value is "+newValue);
}, logContext);
public class SharedThreadContext {
private final ReentrantLock lock = new ReentrantLock();
// private data to protect, as private fields of SharedThreadContext
private final YourProtectedData yourProtectedData1;
public SharedThreadContext(Integer ypdData) {
this.yourProtectedData1 = new YourProtectedData(ypdData);
}
class CustomerDb3 {
private final List<Customers> customers = new ArrayList<>();
private void countOrders(Customer c) {
List<Order> orders;
synchronized(c) {
orders = c.getOrder();
}
class CustomerDb {
List<Customers> customers = new ArrayList<>();
synchronized List<Customers> getCustomers() {
return customers;
}
}
class CustomerUpdater {
class Customer {
String name;
List<Order> orders = new ArrayList<>();
// getters / setters for above.
}