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.
Related
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
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
}
}
I understand that Java instance synchronized methods can run parallel and the static ones will serialize the methods; my lack of understanding is, since the static method locks the Class object, what happens with other Class objects; are we locking between all static classes?
thanks.
Instead of taking the lock on the instance/object you are taking it on the class it self.
When you lock the class you are only locking that class, not all classes.
From the docs
A synchronized method acquires a monitor (§17.1) before it executes.
For a class (static) method, the monitor associated with the Class object for the method's class is used.
For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
Java classes have a monitor associated with the class instance. Since there is only one class instance per class the lock will only be acquired on that class instance.
Now each class defined has its own instance and thus its own monitor, so to answer your question: Synchronizing a static method will only block access to that class.
I'm creating a static class which is going to hold some vectors with info.
I have to make it synchronized so that the class will be locked if someone is editing or reading from the vectors.
What is the best way to do this?
Is it enough to have a function which is synchronized inside the class like this:
public synchronized insertIntoVector(int id)
{
}
Thanks in advance :)
Firstly, you need to define exactly what you mean by "static class". At first, I thought you meant a class where all methods were static (that wasn't meant to be instantiated) - but your code snippet implies this isn't the case.
In any case, synchronized methods inside the class are equivalent to synchronized(this) if they are instance methods, or synchronized(TheContainingClassName.class) if they're static methods.
If you are either creating a non-instantiable class with all static methods, or if you are creating a class that will act as a singleton, then synchronizing every method of the class will ensure that only one thread can be calling methods at once.
Do try to ensure that your methods are atomic though, if possible; calls to different methods can be interleaved by other threads, so something like a getFoo() call followed by a setFoo() (perhaps after incrementing the foo variable) may not have the desired effect if another thread called setFoo() inbetween. The best approach would be to have a method such as incrementFoo(); alternatively (if this is not possible) you can publish the synchronization details so that your callers can manually hold a lock over the class/instance during the entire sequence of calls.
AFAIK, there's no such thing as "static class" in Java. Do you mean a class that contains only static methods? If so, then
public static synchronized void insertIntoVector(int id) {
}
synchronizes with respect to the class object, which is sufficient, if there are only static methods and all of them are synchronized.
If you mean static inner class (where the word "static" has a different meaning than in static methods), then
public synchronized void insertIntoVector(int id)
{
}
synchronizes with respect to an instance of that static inner class.