Is there a way for
java to lock a specific instance variable? for example, i want to lock the product object assuming it's id is 1 (with fields such as: prod id, product name and product price), so that no other threads can access product object with id 1 while other product object with different id (of course not 1) can still be accessed.
i tried locking the object like this way:
private Object Prod;
Prod = ProductFactory.getInstance(1); // this means that product factory will return an instance of product with id 1
public void modifyProduct() // this method modifies a product, which is why i need lock to prevent 2 users from editing the same data, which will lead to dirty reads and data inconsistencies
{
synchronized(Prod) {
}
}
Unfortunately, it doesnt work, and after debugging i found out that different objects being instantiated owns unique and different object id
If i may ask, Are there other ways for me to lock the object, so that no other user can edit the currently editing product object?