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.
Related
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.
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.
When I use synchronized on a method in an interface, the compiler emits an error. Can you tell me why this happens?
What is the reason (logically) that synchronized cannot be applied to a method on an interface?
I tried to make an Interface over Threadpool in this link.
Help me to make Interface in my above code.
Because synchronized is an implementation detail. One implementation of the method might need to make the method synchronized, whereas another one might not need it. The caller doesn't care whether the method is synchronized or not. It's not part of the contract, which tells what the method does. Which synchronization technique, if any, is used to fulfill the contract is irrelevant.
synchronized is an implementation detail and doesn't belong in an interface.
You could have all sorts of implementations that might be threadsafe that don't involve the use of the keyword synchronized.
You might consider using some annotation to indicate the intention that implementations should be thread safe. For example http://jetbrains.dzone.com/tips/concurrency-hot-try-jcip explains how to use the JCIP concurrency annotations.
BTW. Instead of using synchronized, you may want to get cozy with the java concurrent framework. Using low level constructs like synchronized directly is considered a bit of an anti pattern these days.
The simple answer is synchronized is talking about method implementation, but in interface all methods are abstract that means no implementation.
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.
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 )