Here my question is: I have a class with 2 methods one is non static synchronized and another is non static non synchronized method. Now 2 threads trying to access same instance of synchronized and non synchronized methods at a time. What will happen if thread one access non static synchronized method first? Can it be possible second thread to access non static non synchronized method of same instance when first thread apply lock on same instance?
Thanks Chandra
Yes the second thread can access the non synchronised method. There is no lock needed to access the method and can be done so by any thread. If the methods were both in the below format.
1. Static and synchronized. Will have to wait on the class level lock
2. Non static and synchronized. Will have to wait on object level lock
Related
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.
In my recent interview by explaining a situation they asked if the process is thread-safe
There are two synchronized methods one is static and other is not static i.e., non-static Method A and static Method B. These two methods access a shared data.
Now thread A calls non-static method A and thread B is calls static method B. Is this thread safe and explain y?
No, it's not thread-safe. For it to be thread-safe the different threads have to access the shared data using the same lock, but the two methods use different locks. Putting synchronized on a static method uses the class as a lock, putting synchronized on an instance method uses the object as a lock.
If the threads use different locks then neither thread is blocked, and both can access or modify the data concurrently. Even if the threads are only accessing data, and neither modifies it, locking would assure memory visibility. Without the shared lock you can't rely on that visibility. Unrestricted concurrent access would be safe only if the data is immutable and is already safely published.
Assuming the shared data has to be mutable, the fix would be for both methods to use the same lock. You can always specify your own lock if you use a synchronized block (rather than adding synchronized to the method), so the instance method could use:
public void yourInstanceMethod() {
synchronized(WhateverYourClassIs.class) {
// code accessing shared data
}
}
1) Is there a chance that an inner static Runnable class can block if it modifies a static ConcurrentHashMap in the outer singleton, after it calls a Callable? I'm thinking about a scenario where the modification is made to the same item in the map by multiple runnables at the same time. Multiple runnables are ran in a static ThreadPoolExecutor in the outer singleton.
2) Would the callable be called in the same Thread as the runnable, if i do a val = myCallable.call()? It modifies the concurrenthashmap depending on the result of a callable.
ConcurrentHashMap is designed to be non-blocking, although some contention is possible if multiple updates to the same hash segment happened simultaneously.
Yes.
Except when running static initializers, Java will never implicitly block.
call() is a normal method call and will run synchronously in the calling thread, like any other method call.
As per my knowledge in Java class with
Non static synchronize method : lock acquire on particular object
Static synchronize method : lock acquire on class
I am little bit confuse with this, since we can call the static method by class name OR by object name.
Please assume there are 4 methods is my class all are synchronized. 2 methods are static and 2 are not static. If I create 1 object of my class "obj1" and there are 2 threads Thread1 and Thread2 as well
Question 1: if I will try to access the static synchronized method, using the obj1 (or class name), does it mean there is no lock on "obj1", only 2 static methods will be locked (class level lock)? Does this mean another thread can access non-static method, but not the static method using the "obj1" simultaneously?
Question 2: if I will try to access the non-static synchronized method using the obj1 in Thread1, does it mean only 2 methods are locked for Thread2? Does this mean Thread2 can access 2 static methods, OR we can access the static method using the className(MyClass) as well simultaneously?
Question 3: if all the methods in my class are static and synchronized, does it mean there will be no object level lock and there is only one class level lock for all threads?
Please explain little bit about the class level lock.
Even if you call a static method with
someObject.staticMethod()
It doesn't change the fact that the lock is on the Class object. It just means that you're calling static methods in a confusing way and you should call it properly. Just because it works perfectly well, doesn't mean it should be used (unless you intend to make your code less readable).
There's nothing special about the class level lock. It just uses the Class object instead of the instance, and since all static synchronization uses the same Class object, it works like it does.
As for your last question, yes. If you have only static synchronized methods, they will all share the Class object as their lock, no matter how many instances of the class you have created.
I have created 2 objects and 2 threads.
Assume m1() and m2() are synchronized methods.
t1.m1();
t2.m2();
can both threads can execute simultaneously ? is it possible both synchronized methods can execute simultaneously?
Synchronization happens on specific instances. Synchronized methods synchronize on the instances the method is called on. Thus, t1.m1() and t2.m2() can execute simultaneously if and only if t1 and t2 refer to different instances.
Yes, if both are non-static and are executed using two different instances.
Explanation added.
Because monitor is actually associated with the instance. So, if one thread acquired the lock on one instance, the thread is free to invoke the method on the other instance.
They can execute simultaneously, since synchronized methods lock on the instance.
synchronized void someMethod(){
}
is the same as
void someMethod(){
synchronized(this){
}
}
So every instance has its own lock to synchronise on.
Static methods use the class instance instead (SomeClass.class).
Yes, if they are instance methods of different instances, they are synchronization does not happen.
Synchronization is always done on a monitor. Only one thread can access a monitor at a time.
When you are synchronizating methods, the monitor is either the object (non-static) or the Class-object (static methods).
You should think of
public synchronized void myMethod(){
...
}
as:
public void myMethod(){
synchronized (this) {
...
}
}
Since you are having two independent object instances with a synchronized method, you have 2 different monitors.
Result: Both Threads can work simultaneously.