Why we can't declare whole class as synchronized in Java? - 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.

Related

Avoid synchronized at method level

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 confused about using static method in Multithreading java?

something about static:
instances of class share static method
the similar questions:
Java: when to use static methods
What does the 'static' keyword do in a class?
I am confusing about:
static method just have only one memory block?
if i use static method in multithreading, will it block?
I am confusing about:
static method just have only one memory block? if i use static method
in multithreading, will it block?
The static keyword in Java simply means "without regard or knowledge of any particular instance of an object."
An instance method can use this to access the fields of its associated instance, but a static method has no associated instance and so this makes no sense.
In multithreading, thread safety involves protecting the consistency and integrity of mutable data. Because objects encapsulate the state of their instance fields, instance methods only need to be concerned about thread safety in those circumstances in which more than one thread will be accessing the same object.
So while thread confinement of an object is a valid thread safety policy for instances of a class, this same reasoning is invalid for static methods because they have no instance.
This has nothing to do with memory blocks at all. It just has to do with access. An object instance is accessed through a reference. If the reference is thread confined, then the object to which that reference points will always be thread safe. But any thread anywhere that can access your class can potentially get to its static members because no reference to an instance is needed to use them.
Static methods are non-blocking by default. You can implement your own synchronization/thread safety policy and have your static method block if you wish.
Each thread has its own stack space, each time a thread calls a method (static or virtual) that call allocates a stack frame, which holds local variables. nothing about this is specific to static methods.
Static methods can be called concurrently by multiple threads, unless you specifically do something to thwart that, such as requiring that the caller acquire a lock (such as using the synchronized keyword).
Static methods are good for cases where there is no shared state. They may be ok in cases accessing or modifying threadsafe shared state, depending on what level of concurrency is needed and how efficient the threadsafe things being accessed are.
Look out for bottlenecks. Putting the synchronized keyword on a static method may be a problem as that limits your application to calling it with only one thread at a time. Alternative strategies including using atomic objects, using threadsafe data structures designed for high concurrency, or using thread confinement may be preferable to locking.
static method just have only one memory block?
No, methods don't have memory blocks. Threads executing those methods do. Each thread will have it's own memory on the stack where it stores all the method arguments and variables.
if i use static method in multithreading, will it block
A thread cannot access the memory of another thread, but if there is some resource that belongs to all instances and is supposed to be accessed sequentially, then you can synchronize or lock the static method, thus making it a blocking one. Otherwise, no.
Even though there is one instance of a static method, each thread gets its own stack-frame, which means each thread can exercise the same method but in a separate "world" from other threads.
Threads always get their own stack, even for a singleton class (one instance):
so, when to use static methods and when to not?
The main reason for not using static methods everywhere is that they are difficult to unit-test barring manipulating compiled code (Powermock), so static methods should have no dependencies that would require mocking, i.e. the test calls the real method with an input and asserts the output, verbatim, in two steps.
Non-static methods allow you to isolate your test solely to that method by stubbing, mocking, or spying on objects that the method depends on.

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.

How to Application access same arraylist in more than one thread

I am new to java thread application please tell me How to write program, every thread access same list of object in multithreading application?
is there any good link to read?
You can make sure your List (or any Collection) will be thread safe by using the relevant methods in the Collections class.
From the API:
public static <T> List<T> synchronizedList(List<T> list)
Returns a synchronized (thread-safe) list backed by the specified list.
For example
static List mySharedList = Collections.synchronizedList(new ArrayList());
Try to access your list with same instance or make it static and make it Synchronized to make your list thread-safe.
You can use a static list so that there would be only one copy at any time. Also make sure to use syncronised methods for thread-safe.
To access the same instance of your list from all threads, make it static. Eg:
private static List myList;
Then make the accessing method thread-safe (i.e. Make it so that only one thread can access it at one time, so as to avoid conflicts). Eg:
public static synchronized updateList(String parameters) {
// Do something
}
Yes, all threads are able to access the same instance of any objects (incl. classes). Because a memory space is created on per-application (i.e. per-process) basis. Then a process contains all threads inside, incl. implicit 'main' one, with shared memory space.
If an object is used in one thread only, there are no any concurrency issues. You need no any 'synchronization', locking etc. But sometimes you may have to share something between thread. If both reading and writing can be done in a few threads simultaneously, it means you need synchronize by this object to deal with so called 'racing'.
You don't have to make a field as static for a shared object to make it thread-safe. If necessary, you can just pass this object as a parameter into a class which extends Thread class (or it may be even a local variable in enclosing class method in case of anonymous class, etc.)
So all you need is just synchronize by this object. You can synchronize either explicitly inside a method:
synchronized (obj) {
// doing a thread-safe stuff
}
or you can make a method synchronized entirely for an obj's class using such method modifier. In this case it will be synchronized implicitly and automatically on invocation of the method like "synchronized (this) {..}" block:
public void synchronized methodFoo() {
}
As for reading, I read 'Java in a Nutshell', chapter 5.7. "Threads and Concurrency". It was very helpful for me because of overview of all multi-threading possibilities in Java.
Among online resources, official Sun/Oracle's tutorial may be helpful for the beginners: http://docs.oracle.com/javase/tutorial/essential/concurrency/ (which has been already mentioned in another answers).

Categories