This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I want to create a utility class that will contain multiple static methods to handle the monotonous task throughout my application.
public static synchronized String checkIfNull(String s) - will return empty "" if null
public static synchronized boolean checkIfError(String s) - will take a String value, return false if null or else parse and return the boolean
Now because static methods synchronize using the Class object, is the following true?
If a thread calls methodA, and another calls methodB immediately after that, the thread calling methodB will have to wait for the lock on methodA to release as the lock is done at class level?
However, if your class has no data of its own (so no static fields) and also does not rely on any external source (like a database), then synchronization is only slowing down your application. In your example, there is no reason methodA and methodB, or even two parallel calls to methodA, should not be allowed to run together.
And what would be the point of such synchronization? If you want to synchronize the threads (eg. to avoid race condition, protect some resources etc.), you should do it externally (ie. in the MyThread class for instance), not in the utility class. Utility class is a kind of a library - you wouldn't want libraries to determine how your application is synchronized, would you? Now, if the only point is to have the log messages be written nicely in order... that's a bit tougher. I'd propose to output the thread ID and/or some other ID for each thread. Some logging frameworks like log4j can do it for you. Then you can brows the logs and trace which call was in which thread. Synchronizing just to get the log entries in order could result in a big performance penalty.
Rob Prime wrote:
and also does not rely on any external source (like a database)
Yes it does - System.out. That's also an external source, namely the system console. As you need your enter and return messages to be grouped on the system console synchronization all of a sudden makes more sense.
Joined: Jan 31, 2006
Thanks Adam and Rob.
Okay, I added the SOP's to test, and maybe jeopardized my own theory if the method should be synchronized or not ...
Basically, I want my methods in the utility class to behave exactly like Math.random().
So it will take a value and maybe do some calc / modification and return a value. No values or resources to consider, or dependencies on external resources.
No. Two different threads will share nothing at all (well, the CPU maybe ) and have no precedence relation ship (e.g. methodA must always be finished before methodB starts) so you don't need synchronization.