Avoid synchronized at method level - java

PMD (source code analyzer) recommends to avoid synchronized at method level.
It is actually obvious as when you call synchronized on method you are calling synchronized on this and that can lead to potential issues.
But PMD in this rule suggests the following example: Synchronized on method rule
public class Foo {
// Try to avoid this:
synchronized void foo() {
}
// Prefer this: <----- Why? Isn't it the same on byte-code level
void bar() {
synchronized(this) {
}
}
}
Is it a bug in a specification of PMD (in the example) or synchronized on method works differently from synchronized(this)?

Yes, it is technically the same. This is about code style, not correctness.
The link you posted explains the reason quite well:
Method-level synchronization can cause problems when new code is added
to the method. Block-level synchronization helps to ensure that only
the code that needs synchronization gets it.

The “correct” versions are bugs in the PMD documentation, at the very least.
The point of the rule is to indicate that placing an entire method body in a synchronization block is probably unnecessary; in most cases, only the code accessing a multi-threaded resource needs to be synchronized. So the examples should show, or imply, that there is some code before and/or after the synchronized block.

An additional rule in SB_CONTRIB discourages use of this in synchronized since the class object can be used by other threads to lock on as well.
http://fb-contrib.sourceforge.net/bugdescriptions.html
NOS_NON_OWNED_SYNCHRONIZATION
This method uses a synchronize block where the object that is being synchronized on, is not owned by this current instance. This means that other instances may use this same object for synchronization for their own purposes, causing synchronization confusion. It is always cleaner and safer to only synchronize on private fields of this class. Note that 'this' is not owned by the current instance, but is owned by whomever assigns it to a field of its class. Synchronizing on 'this' is also not a good idea.
In conjunction with this Spotbugs rule, it is more than good style to not synchronize the entire method body.

Related

Why we can't declare whole class as synchronized in Java?

I am new to Java I just want to know what if whole class in Java will be synchronized, what will be the possible problems? I know the concept of class level locking, which is different.
Marking the whole class synchronized would be misleading. Although there are situations when it makes perfect sense to make all methods of a class synchronized, a class typically contains other declarations that cannot be synchronized.
For example, class constructor cannot be marked synchronized. Same goes for fields of a class. One could mistakingly assume that fields in a class marked synchronized would be accessed in a synchronized way, but that is not something that Java does automatically. Of course language designers could declare that synchronized on class level applies only to methods, but such decision would be somewhat arbitrary.
The synchronized keyword can only be used on method declarations and as synchronized blocks. When used on a method declaration, it's the same as adding a synchronized block around the contents of the method, synchronizing on this. There is nothing preventing you from synchronizing every method of a class. If you use synchronized keyword on every method declaration that would mean that only one method of the class can execute concurrently. In a multi-threaded application this could cause poor performance, but there isn't anything to prevent you doing it.

Why "synchronized" has no role in polymorphism

synchronized is not part of method signature. But when we override a method, its not only the method signature which decides whether the overridden method will compile or not.
For example, we cannot add or widen a checked exception
Why does synchronized have no role in polymorphism. A synchronized method should not be overridden without putting synchronized. As the person who is using super class variable might think that all methods are thread safe.
But a non synchronized methods should be allowed to be overridden with synchronized as it is adding more functionality but on the other hand user will not face any error except time lag.
I am looking a logical explanation which can throw some light on "why is designed so".
A "synchronized" method should not be overridden without putting "synchronized".
Wrong. A base class might not be thread-safe, but a subclass might have its own synchronization, such as a lock, lock-free thread-safe data structure, etc. Not all thread-safe methods are synchronized, and not all synchronized methods are thread-safe.
The same can go in the other direction (but may break other principles, depending on the case)
synchronized isn't an object-oriented thing, but rather a runtime/execution phenomenon, and an implementation detail. All it does is acquire a monitor the same way synchronized(this){ } (or synchronizing on the java.lang.Class object if static) would. As an implementation detail, it makes no sense to expose it to OOP considerations.
Note: This doesn't mean that a compile-time annotation such as #ThreadSafe doesn't make sense. It does, since it references the method's contract to be thread-safe. synchronized doesn't do this.
You can see JDK-4294756 for an explanation of it is OK for a method to override another without preserving the synchronized modifier. This bug report asked for a warning to be shown by the compiler when a method overrides a synchronized method but does not declare itself synchronized, and it was closed as "Won't Fix". The key reason is the following:
The use of the synchronized modifier, as well as other synchronization via
explicit 'synchronized' statements, is a part of the implementation of an
abstraction represented by a class, and an alternate implementation captured
in a subclass may use a different synchronization strategy in order to
implement equivalent semantics. As an example, consider the case in which a
small critical section (protected by a 'synchronized' statement) within a larger
unsynchronized method replaces a smaller method that was protected in its
entirety by a synchronized method modifier.
So the absence of a synchronized modifier does not necessarily mean the method is not thread-safe. Thread-safety can be fine-grained inside the method.
Let me put it a different way:
Suppose we have two classes:
class Foo {
public synchronized void doSomething(...) { ... }
}
class Bar extends Foo {
public void doSomething(...) { ... }
}
Foo and Bar are different classes. foo.doSomething(...) and bar.doSomething(...) are different methods.
The synchronized keyword is not there for the benefit of the caller: It says nothing about what foo.doSomething(...) does. The synchronized keyword is just a detail of how that method is implemented.
The Foo class needs its doSomething(...) method to be synchronized in order to correctly fulfill its API contract in a multi-threaded environment. The bar.doSomething(...) method is implemented differently and it doesn't need synchronization.
So long as a Bar instance can be used wherever a Foo instance is wanted, everyone should be happy. There's no reason why the caller should want the method to be synchronized: The caller should just want the method to work.

Why can't an abstract method be synchronized?

I was reading a thread from CodeRanch saying that abstract methods could not be synchronized due to the fact that an abstract class cannot be instantiated, meaning no object to lock.
This doesn't make sense since an abstract class is a definition (contract) for a child class. The abstract definition of a synchronized method does not need to lock, the child does. All the abstract heading would indicate is that the child must synchronize this method. Is my logic on this correct? If not can someone explain why I'm wrong?
The comment about not being able to instantiate the abstract class is garbage. Given that it has to be an instance method to be abstract, there certainly is a reference which could be locked on. Concrete methods in abstract classes can still refer to this. However, that still doesn't mean that abstract classes should be able to be synchronized.
Whether or not a method is synchronized is an implementation detail of the method. Synchronization isn't specified anywhere as a declarative contract - it's not like you can synchronize in interfaces, either.
How a class implements whatever thread safety guarantees it provides is up to it. If an abstract class wants to mandate a particular approach, it should use the template method pattern:
// I hate synchronizing on "this"
private final Object lock = new Object();
public final void foo() {
synchronized(lock) {
fooImpl();
}
}
protected abstract void fooImpl();
That's pretty dangerous in itself though, given that it's effectively calling "unknown" code within a lock, which is a recipe for deadlocks etc.
Locking behavior shouldn't be specified using abstract methods or interface methods because it shouldn't be part of the contract.
Probably the idea was that locking behavior is fundamentally part of the implementation -- different implementations will want to perform locking differently -- and it would be counterproductive to specify it at that level of abstraction.
Remember the keyword synchronized is specifically for implementing implicit locking (acquiring the lock on the object that the instance method is called on), and there are ways to do locking using alternatives like ReentrantLock, where that keyword is not applicable, or possibly to use CAS or otherwise avoid locking altogether.
synchronized void foo()
{
body
}
is defined to be equivalent to
void foo()
{
synchronized(this)
{
body
}
}
(if static, synchronized on the class instead of this)
Since an abstract method has no body, synchronized keyword on the method is undefined.
I think one logic behind that could be that whether or not to synchronize that method should be decided by the implementing class. Meaning, it gives the freedom to the implementer to choose on whether to provide a synchronized or unsynchronized implementation. Plus, the client would also have option to to select the unsynchronized version so as to avoid synchronization overhead if thread-safety is not an issue.

String Utils - Java

I've created a StringUtil class which is used for some string validation across the application. The code for the StringUtil is as below,
public class StringUtil {
public static synchronized boolean isValidString(String string) {
return string!= null && string.trim().length() > 0;
}
}
In this class the method checks whether the string is a valid string or not. This method is thread safe. In an enterprise application, there might be multiple threads accessing this method. If a thread is accessing this method, then all the other threads have to wait for its turn. This method in turn will be used very frequently to check the string for null values. So which is the best option
Making this a singleton and thread safety
Making this as instance method
Is there are any other way to organize a pool with objects of this type and each thread would pick up one and release the object to the pool once done.So thread safety is not a concern and object creation is also not done.
Are are there any open source libraries for the same.
Since you don't have any state here (you only use the method argument string), the method is inherently thread safe. Therefore there is no need to use the synchronized keyword.
If the method is used throughout your project, just declaring it static as you have already done is the best option.
Usually helper methods like this, are public static, and not synchronized, because the class doesn't hold state. Since it doesn't hold state neither, you don't need a pool.
I think a good example of this the apache commons StringUtils class.
I have the feeling that you're trying to use a neutron cannon to open a walnut, simplicity is king :)
You could try the util classes from Apache Commons.
But you have thread-safety here anyway, since you're not manipulating anything in the class that other calls might read (i.e. you have no state).
You should probably use the StringUtils class in Apache Commons.
This method should not be synchronized because it does not use any class level variables. So multiple threads can concurrently access it without any problem.
Moreover forget about synchronization when you are writing code for enterprise application that is running into container. It is container's responsibility to care about thread safety. synchronized blocks just bother the container to do its job. If you need synchronization in enterprise application re-think your design and/or find other patters (there are a lot) to solve your problem.
There is no need of synchronized keyword since String is immutable object
Immutable objects are often useful because they are inherently thread-safe
public static boolean isValidString(String string) {
return !(string== null || string.isEmpty()); //Since 1.6
}
Utility classes usually contain only static methods therefore it always a good idea to state explicitly that these classes were not designed to be instantiated. Therefore make their constructor private:
public class StringUtils {
private StringUtils() {
throw new AssertionError("shouldn't be instantiated");
}
}
(see Joshua Bloch's Bible : Item 4: Enforce noninstantiability with a private constructor )

Cascading synchronization with Java

I tried really hard to search for information about the issue, but nothing was relevant.
Any contribution will be appreciated.
DataStructure ds = new DataStructure();
public synchronized void run() { b(); }
private void b() { ds.update(); }
public synchronized void c() { ds.update(); }
Suppose that the above code is implemented using a thread.
as you might notice, there is a DataStructure object which is being shared and accessed through synchronized methods, when only one synchronized method can be called at any given time (I am not mistaken. right?).
Is there any possibility that the DataStructure object will be accessed through the public methods in unsynchronized manner?
thanks.
Your code is incomplete, but if the above is part of a Runnable or Thread, then no concurrency is possible with the given methods since you're synchronizing the entire run() method. Using threads is pretty pointless in that case.
I also don't see where the DataStructure would be shared between threads - looks like a separate one is created for each one. If it actually is shared, then access would not be synchronized because you synchronize on the Runnable or Thread rather than the shared object.
Without seeing more code, its very hard to tell. What is the class that those methods belong to? how are they invoked, and by what classes?
Concurrency problems are hard to diagnose, and harder if there isn't enough information.
What i assume you have are threads that execute the run() method above, and there are different threads that execute the c() method. The synchronization happens on the class that the above method resides, so there wouldn't be any problems (except slowness if lots of threads).
If
There is no other public method apart from what you wrote here, that has access to ds, and
"the DataStructure object" you are talking on is the object instance in a specific object instance of your class (instead of ALL DataStructure objects)
then what you are expecting is correct. There shouldn't be any concurrent access to ds through public methods of your class.
Honestly I don't see anything special in your class that make it different from normal synchronized method example.

Categories