Hello All,
I have a question related to synchronization in java; there's more like a confirmation. Let's start with the simplified version of my class:
class MyClass {
private List<MyObject> myList = new ArrayList();
public void addEntry(MyObject obj) {
myList.add(obj);
}
public void removeEntry(MyObject obj) {
myList.remove(obj);
}
public double computeAValue() {
//
// Compute a value based on myList
//
}
public double computeBValue() {
//
// Compute a value based on myList
//
}
......
}
I need to make the class thread safe... which means the following:
- don't let a thread add / remove entries in the underlying collection while computing values
- actually in plain english: I want to prevent any two methods being executed by different threads in the same time
For this to achieve I have the following solutions
- make each method sinchronized
- use a lock object at instance level and protect code blocks with
method body .... synchronized(myLock) { try { } catch(Exception e) { ... } finally { myLock.notifyAll(); } } .... end method body
Solution 2 looks a little messier since I would have to store locks on the exterior of the class, but I'm sure it will work since there's a construction already used and tested.
The main question refers to synchronized keyword: would it achieve my requirement? I'm sure it won't let two threads execute the same method simultaneously, but would it apply to all synchronized method at the instance level?
The java lang specs states:
A synchronized method acquires a monitor before it executes. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
This would suggest that my goal would be reached by making the methods synchronized.
Can you confirm this? Have you actually wrote code to teste this assumption or successfully used it in a production environment?
Thank you,
Marius