Results 1 to 4 of 4
- 08-27-2011, 05:23 PM #1
Member
- Join Date
- Jul 2009
- Posts
- 4
- Rep Power
- 0
correct argument to put in synchronized method
Hi guys,
I am wondering what is the proper argument to pass in a synchronized method:
Please kindly advice. Thanks in advance!Java Code:public void method1() { synchronized( this ) { .... } } public void method1() { synchronized( MyClass.class) { .... } } public void method1() { synchronized( MyClass.class) { .... } } public void method1() { A objecta=new A(); synchronized( objecta) { .... } }
Cheers,
Mark ThienLast edited by sunde887; 08-27-2011 at 05:27 PM. Reason: Added code tags, [code]...[/code]
- 08-27-2011, 05:44 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
We cannot tell you which one is right. It depends on what do you want to do :)
Intrinsic Locks and Synchronization (The Java™ Tutorials > Essential Classes > Concurrency)
- 08-27-2011, 06:49 PM #3
There is no requirement to pass any arguments to a synchronized method.what is the proper argument to pass in a synchronized method
- 09-07-2011, 01:27 AM #4
Member
- Join Date
- Feb 2011
- Posts
- 3
- Rep Power
- 0
Re: correct argument to put in synchronized method
Synchronized segments in your code can only be executed by a single thread at a time for which the same object was provided as an "argument". Therefore...
public void method1() {
synchronized( this ) {
....
}
}
method1() cannot run simultaneously for a given instance. This is the same as 'public synchronized void method1() {...}'
public void method1() {
synchronized( MyClass.class) {
....
}
}
method1() cannot run simultaneously for any instance
public void method1() {
A objecta=new A();
synchronized( objecta) {
....
}
}
No synchronization since each call to method1() synchronizes on a different object
Similar Threads
-
calling yield() method in synchronized block
By Ash-infinity in forum New To JavaReplies: 2Last Post: 12-04-2012, 05:35 PM -
The differences made by Synchronized method
By dav in forum Threads and SynchronizationReplies: 3Last Post: 05-25-2011, 02:49 PM -
Method as an argument?
By StokedOnMe in forum New To JavaReplies: 13Last Post: 09-18-2009, 06:29 AM -
Servlet behaving badly unless method is synchronized
By domanows in forum Java ServletReplies: 0Last Post: 01-29-2009, 02:37 AM -
[SOLVED] Non-synchronized instance method of an Object
By piyu.sha in forum Threads and SynchronizationReplies: 2Last Post: 10-06-2008, 06:35 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks