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

  1. make each method sinchronized
  2. 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

At the simplest, yes, simply make the methods synchronised as that will cause them to sync on the instance of the class.

1. Although the option 2 is better from performance point of view as YOU decide exactly which statements within the method are synch'd.
2. Even the statements that access the data from underlying storage need to be synch'd.

Well, if you don't declare the method synched, its not synched. But, if you meant, you can control which portions of the method are synched, yes. ;-)

Well, if you don't declare the method synched, its not synched. But, if you meant, you can control which portions of the method are synched, yes. ;-)

I also didn't completely get your comment (like you didn't get mine :)).
What I meant was do NOT declare the method synch'd. Inside the implementation (of the method) put synch for required statements "manually" (somethihg like what he posted in the original question).

Well, you had said that doing the sync inside the method will allow the programmer to control which methods are synched. Well, you can do that with the synchronized keyword as well. Simply do not declare the methods you do not want to be synched as synchronized. Now, if you want to be able to control, for example, that only the excution of two lines out of a hundred line method are synched, then, yes, do the synchronization inside the method. But, if you are going to synch on the current instance, and the entire (or nearly the entire) method's content will be synched, then there is no reason not to use the synchnronized keyword on the method.

Hello All,

Thank you for the answers, I guess I was overcautious on this. My understanding of synchronized (which was not complete) involved threads not executing the same synchronized method when in fact the synchronized protection spans across methods that are marked as synchronized.

NetBeans IDE along with its Profiler provides a nice visual representation of the threads and their states in real-time. I have created a project that you can find attached and couple of executions with two sets of parameters.

The execution2.txt / threads2.gif show how Worker_2 waits on adding new elements while Worker_1 is finishing the getListAsStrings() method.


All the best,
Marius

Well, you had said that doing the sync inside the method will allow the programmer to control which methods are synched. Well, you can do that with the synchronized keyword as well. Simply do not declare the methods you do not want to be synched as synchronized. Now, if you want to be able to control, for example, that only the excution of two lines out of a hundred line method are synched, then, yes, do the synchronization inside the method. But, if you are going to synch on the current instance, and the entire (or nearly the entire) method's content will be synched, then there is no reason not to use the synchnronized keyword on the method.

We're on the same page. Perhaps you read my post too quickly. I said "which statements within the method".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.