File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes Synchronized Block and Synchronized Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "Synchronized Block and Synchronized Method" Watch "Synchronized Block and Synchronized Method" New topic
Author

Synchronized Block and Synchronized Method

Pieter Jacobs
Ranch Hand

Joined: May 20, 2009
Posts: 87
Hi again,

Is is still considered good practice to have synchronized methods as well as some methods just standard with a synchronized block in the same class?

Personally I think it is alright, but would like to bounce it off you guys.

Thanks,
Pieter
Carlos Morillo
Ranch Hand

Joined: Jun 06, 2009
Posts: 221

Hi Pieter,


The simpler the code the easier it will be for a junior developer to maintain your code.
Since a high performance solution is not a MUST requirement, the use of synchronized methods is OK.

Just make sure you mention it in your choices.txt file.

Hope this helps.


Best,


Carlos.


SCSA, OCA, SCJP 5.0, SCJD http://www.linkedin.com/in/carlosamorillo
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5266
    
  13

Hi Pieter,

I think there is no harm in mixing synchronized methods with synchronized blocks. I didn't do it, because (like Carlos also mentioned) I took the as simple as possible approach (and performance wasn't a must requirement).

Kind regards,
Roel


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Pieter Jacobs
Ranch Hand

Joined: May 20, 2009
Posts: 87
Hi Carlos & Roel,

Thanks for the replies!! So you guys also marked your public methods as synchronized and left the private methods standard (unsynchronized)?

Thanks,
Pieter
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 5266
    
  13

Hi Pieter,

That's indeed exactly what I did, because every public method is synchronized, every private method is used from a synchronized context and there is no need to mark them synchronized as well (but you just might do it).
If you use synchronized blocks, you have to mark private methods synchronized if you want that just one thread can access this method at a time (and other threads need to wait until that thread finishes the method).

Kind regards,
Roel
Pieter Jacobs
Ranch Hand

Joined: May 20, 2009
Posts: 87
Hi Roel,

Mega thanks again!

Enjoy the week,
Pieter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronized Block and Synchronized Method