Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to lock a specific instance variable  RSS feed

 
Ryann Ong
Greenhorn
Posts: 19
Fedora Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey.

The best idea is usage of the immutable Product objects in your design. Consider it first and foremost.
Otherwise, you must be assured of existing only ONE instance of the Product for a given "id" per JVM. Your ProductFactory class should ensure it.

The simplest, but somewhat clumsy example below:



Assumption: The MutableProduct(int id, String name, BigDecimal price) constructor has "package-private" level of access control and is invoked and managed only by ProductFactory.

Adam
 
Ryann Ong
Greenhorn
Posts: 19
Fedora Java PHP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Adam, I'm going to try this one, hope this would work, but i also found out that using the factory pattern could help. Now im currently reading on it also,
 
Andrei Matyas
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Do not forget that in theory an immutable object must:

* the class cannot be overridden so make it final
* all fields are private and final
* the object should be constructed completely in a single step (no setter methods)
* do not provide methods which can change the object

 
Andrei Matyas
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see some synchronized methods .....a well implemented immutable object is automatically thread-safe and have no synchronization issues
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!