Synchronizing static methods - java

I'm writing code that requires some synchronization between a few static methods. My goal is to block the execution of any of these methods if one of them executes.
So for example:
public class Foo{
static Object lock = new Object();
static List<SomeObject> listOfObjects = new ArrayList<>() ;
public static void methodA() {
synchronized (lock) {
//Do some stuff
methodB();
}
}
public static List<SomeObject> methodB() {
synchronized (lock) {
//Do some stuff
return listOfObjects;
}
}
}
Now let's assume that the following is executed from somewhere in the code:
Foo.methodA();
Foo.methodB();
My questions are:
Is it actually synchronized? will methodA and methodB won't run concurrently?
If so, will methodA calling methodB create a deadlock?

Answers:
"Is it actually synchronized? will methodA and methodB won't run
concurrently?" - yes, these methods are synchronised. More precisely, code blocks in methods are synchronised.
"If so, will methodA calling methodB create a deadlock?" - no, synchronized keyword is re-entrant in nature it means if a synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock" - from 1
You could improve code a little by providing private and final keywords:
private static final Object lock = new Object();
Also, do not return direct reference to a List you want to protect. Return read only view:
return Collections.unmodifiableList(listOfObjects);
Since now, client has only read only access which protects you from many unexpected situations.
Static versus non-static lock object in synchronized block
Object level lock vs Class level lock in Java

Is it actually synchronized? will methodA and methodB won't run
concurrently?
Yes, this synchronization looks good.
A thread can acquire the same lock multiple times, increasing a lock counter. And after it releases all of them, only then another thread can acquire that lock.
In your code, a thread calling methodA() acquires the lock twice, once in methodA() and then in methodB(). Then it releases them twice (when the synchronized blocks end).
If so, will methodA calling methodB create a deadlock?
No, as explained above, it won't create a deadlock unless you are doing some operations in those methods that can take forever to complete, in which case there will be starvation. If you are not doing any such operation, then I don't think you can get a deadlock when you are using only one lock.

Nope. Method A and method B WILL run concurrently because it's not the methods that are synchronized but the code inside. The code will continue normally with whichever has the lock. Then the other method will finish.
public class Foo1 {
static Object lock = new Object();
static List<Integer> listOfObjects = new ArrayList<>();
public static void main(String[] args) {
new Foo1().start();
}
public void start() {
new Thread(() -> methodA()).start();
// method A has the lock
sleep(1000); // sleep 1 second
// but method B is still entered and prints first
new Thread(() -> methodB()).start();
}
public static void methodA() {
sleep(5000); // sleep 5 seconds
System.out.println("Entering methodA()");
synchronized (lock) {
// Do some stuff
methodB();
}
}
public static List<Integer> methodB() {
System.out.println("Entering methodB()");
synchronized (lock) {
// Do some stuff
return listOfObjects;
}
}
static void sleep(int milli) {
try {
Thread.sleep(milli);
}
catch (InterruptedException ie) {
}
}
}

Related

understanding nested locks in java

i want to understand this:
String string;
public Test(String string){
this.string = string;
.....
}
public void foo(newObjectPerCall o) {
synchronized (o) {
//each thread can enter here because the object passed is always different
....
synchronized (string) {
// acquire this lock if the String is free.
}
}
}
public synchronized void function() {
}
public static void main(){
Test test = new Test("hello");
for(int i = 0; i < 10;i++){
WorkerThread workerThread = new WorkerThread(test);
workerThread.start();
}
}
thread class
public class WorkerThread extends Thread {
private Test test;
public WorkerThread(Test test) {
this.test = test;
}
#Override
public void run() {
while (true) {
test.foo(new Object());
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test.function();
}
}
}
my doubts are:
if one thread acquire the inner lock, other threads that acquired the outer lock, will remains inside the foo function?
When on thread ,for some reasons, remains outside the foo function, can this one acquire the lock of test instance inside function?
if one thread acquire the inner lock, other threads that acquired the outer lock, will remains inside the foo function?
Yes. They will block, waiting to acquire the monitor for string.
When on thread ,for some reasons, remains outside the foo function, can this one acquire the lock of test instance inside function?
Yes, it's entirely independent of the other monitors. A synchronized instance method is just equivalent to one whose body is
synchronized (this) {
...
}
If no other thread already owns the monitor for this, the "new" thread can acquire it regardless of what other monitors are owned. But as all your worker threads are using the same instance of Test, only one of them will be able to be "in" function() at a time. That can be at the same time as another thread is executing foo() though.
Sorry I know only the answer only for the first question
if one thread acquire the inner lock, other threads that acquired the outer lock, will remains inside the foo function?
Yes

Thread 1 is executing in java synchronized method 1, can Thread 2 then execute in java synchronised method 2?

Was wondering if someone could help clear this up for me. (Student)
Say we have two threads, "Thread1" & "Thread2". If Thread1 is executing in method 1 can Thread2 then execute in method2?
void method1() {
synchronized (this) {
}
}
void method2() {
synchronized (this) {
}
}
I'm either thinking yes, Thread2 can enter as "this" is just the instance of that method or no because "this" is the instance of that class and Thread1 holds onto it.
There isn't a monitor associated with a specific method - there's a monitor associated with an object. So if you're trying to synchronize on the same object in both methods, the second thread will block until the first thread releases the monitor.
(Personally I don't like synchronizing on this anyway - I synchronize on a reference to an object that only my class has access to. But that's a different matter.)
Everybody jumped on an obvious answer here. It is a correct answer, but it is not the only correct answer.
The rule is, two threads can not both synchronize on the same object at the same time. But does this refer to the same object in both method calls? We can't tell because you have not shown us the calls. Consider this example:
class Demo {
synchronized void method1() {
...do something...
}
synchronized void method2() {
...do something else...
}
static void caseA() {
final Demo demo = new Demo();
new Thread(new Runnable(){
#Override
public void run() {
demo.method1();
}
}).start();
new Thread(new Runnable(){
#Override
public void run() {
demo.method2();
}
}).start();
}
static void caseB() {
final Demo demo1 = new Demo();
final Demo demo2 = new Demo();
new Thread(new Runnable(){
#Override
public void run() {
demo1.method1();
}
}).start();
new Thread(new Runnable(){
#Override
public void run() {
demo2.method2();
}
}).start();
}
}
In caseA(), the calls to demo.method1() and demo.method2() can not overlap because both calls synchronize on the same object, but in caseB() the two calls are synchronized on two different instances of the Demo class. In caseB() the method1() call and the method2() call can overlap.
You are using this for synchronization, which is an instance of an object. Synchronization always works on some particular instance of object and only one thread at any given time can acquire lock of (synchronize on) a single instance used for synchronization and.
Both threads can access the methods only if they use separate instances of the object containing those methods.
The second thread will block until the monitor is released by the first as synchronization is done on the same object for both methods.
You'd better synchronized on the static object you want to lock.
Here, your method 2 will be executed by thread 2, but the content of the synchronized block in method 2 will not be executed unless thread 1 has unlock this. Since your synchronization is on a block, and not on a method, the method is not synchronized, but the block is.
If you have a static member on which you want work in the synchronized, use it like:
private static List<Object> myList;
void method1() {
synchronized (myList) {
// do something on myList
}
}
void method2() {
synchronized (myList) {
// do something on myList
}
}
No Thread2 will have to wait until Thread1 is finished executing the code in synchronised block. This is because you are using the same object (this) to lock. If you did something like this:
Object lock1 = new Object();
Object lock2 = new Object();
void method1() {
synchronized (lock1) { }
}
void method2() {
synchronized (lock2) { }
}
Then you would be able to have Thread1 execute method1 and Thread2 execute method2.

Why is synchronized block better than synchronized method?

I have started learning synchronization in threading.
Synchronized method:
public class Counter {
private static int count = 0;
public static synchronized int getCount() {
return count;
}
public synchronized setCount(int count) {
this.count = count;
}
}
Synchronized block:
public class Singleton {
private static volatile Singleton _instance;
public static Singleton getInstance() {
if (_instance == null) {
synchronized(Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
When should I use synchronized method and synchronized block?
Why is synchronized block better than synchronized method ?
It's not a matter of better, just different.
When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:
public synchronized int getCount() {
// ...
}
This is just like you wrote this.
public int getCount() {
synchronized (this) {
// ...
}
}
If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.
The difference is in which lock is being acquired:
synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.
synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.
So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.
If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.
This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.
Although not usually a concern, from a security perspective, it is better to use synchronized on a private object, rather than putting it on a method.
Putting it on the method means you are using the lock of the object itself to provide thread safety. With this kind of mechanism, it is possible for a malicious user of your code to also obtain the lock on your object, and hold it forever, effectively blocking other threads. A non-malicious user can effectively do the same thing inadvertently.
If you use the lock of a private data member, you can prevent this, since it is impossible for a malicious user to obtain the lock on your private object.
private final Object lockObject = new Object();
public void getCount() {
synchronized( lockObject ) {
...
}
}
This technique is mentioned in Bloch's Effective Java (2nd Ed), Item #70
Difference between synchronized block and synchronized method are following:
synchronized block reduce scope of lock, but synchronized method's scope of lock is whole method.
synchronized block has better performance as only the critical section is locked but synchronized method has poor performance than block.
synchronized block provide granular control over lock but synchronized method lock either on current object represented by this or class level lock.
synchronized block can throw NullPointerException but synchronized method doesn't throw.
synchronized block:
synchronized(this){}
synchronized method:
public synchronized void fun(){}
Define 'better'. A synchronized block is only better because it allows you to:
Synchronize on a different object
Limit the scope of synchronization
Now your specific example is an example of the double-checked locking pattern which is suspect (in older Java versions it was broken, and it is easy to do it wrong).
If your initialization is cheap, it might be better to initialize immediately with a final field, and not on the first request, it would also remove the need for synchronization.
synchronized should only be used when you want your class to be Thread safe. In fact most of the classes should not use synchronized anyways. synchronized method would only provide a lock on this object and only for the duration of its execution. if you really wanna to make your classes thread safe, you should consider making your variables volatile or synchronize the access.
one of the issues of using synchronized method is that all of the members of the class would use the same lock which will make your program slower. In your case synchronized method and block would execute no different. what I'd would recommend is to use a dedicated lock and use a synchronized block something like this.
public class AClass {
private int x;
private final Object lock = new Object(); //it must be final!
public void setX() {
synchronized(lock) {
x++;
}
}
}
In your case both are equivalent!
Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.
In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.
public static synchronized int getCount() {
// ...
}
is same as
public int getCount() {
synchronized (ClassName.class) {
// ...
}
}
One classic difference between Synchronized block and Synchronized method is that Synchronized method locks the entire object. Synchronized block just locks the code within the block.
Synchronized method: Basically these 2 sync methods disable multithreading. So one thread completes the method1() and the another thread waits for the Thread1 completion.
class SyncExerciseWithSyncMethod {
public synchronized void method1() {
try {
System.out.println("In Method 1");
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Catch of method 1");
} finally {
System.out.println("Finally of method 1");
}
}
public synchronized void method2() {
try {
for (int i = 1; i < 10; i++) {
System.out.println("Method 2 " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Catch of method 2");
} finally {
System.out.println("Finally of method 2");
}
}
}
Output
-------
In Method 1
Finally of method 1
Method 2 1
Method 2 2
Method 2 3
Method 2 4
Method 2 5
Method 2 6
Method 2 7
Method 2 8
Method 2 9
Finally of method 2
Synchronized block: Enables multiple threads to access the same object at same time [Enables multi-threading].
class SyncExerciseWithSyncBlock {
public Object lock1 = new Object();
public Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
try {
System.out.println("In Method 1");
Thread.sleep(5000);
} catch (Exception e) {
System.out.println("Catch of method 1");
} finally {
System.out.println("Finally of method 1");
}
}
}
public void method2() {
synchronized (lock2) {
try {
for (int i = 1; i < 10; i++) {
System.out.println("Method 2 " + i);
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Catch of method 2");
} finally {
System.out.println("Finally of method 2");
}
}
}
}
Output
-------
In Method 1
Method 2 1
Method 2 2
Method 2 3
Method 2 4
Method 2 5
Finally of method 1
Method 2 6
Method 2 7
Method 2 8
Method 2 9
Finally of method 2
It should not be considered as a question of best for usage, but it really depends on the use case or the scenario.
Synchronized Methods
An entire method can be marked as synchronized resulting an implicit lock on the this reference (instance methods) or class (static methods). This is very convenient mechanism to achieve synchronization.
Steps
A thread access the synchronized method. It implicitly acquires the lock and execute the code.
If other thread want to access the above method, it has to wait. The thread can't get the lock, will be blocked and has to wait till the lock is released.
Synchronized Blocks
To acquire a lock on an object for a specific set of code block, synchronized blocks are the best fit. As a block is sufficient, using a synchronized method will be a waste.
More specifically with Synchronized Block , it is possible to define the object reference on which are want to acquire a lock.
Because lock is expensive, when you are using synchronized block you lock only if _instance == null, and after _instance finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.

How Java manage following scenario?

I tried some code to justify the reliability of synchronized block locking mechanism. Consider my sample code
My clocking object.
public class MyLock {
final static Object lock=new Object();
}
Class with synchronized blocks
public class Sample {
public void a(String input) {
System.out.println(input+" method a");
synchronized (lock) {
System.out.println("inside synchronized block in a");
try {
System.out.println("waiting in a");
Thread.sleep(5000);
System.out.println("calling b() from a");
new Sample().b("call from a");
System.out.println("waiting again in a");
Thread.sleep(5000);
System.out.println("Running again a");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void b(String input) {
System.out.println(input+" method b");
synchronized (lock) {
System.out.println("bbb " + input);
}
}
}
Test1 class
public class Test1 implements Runnable{
public static void main(String[] args) {
new Thread(new Test1()).start();
new Thread(new Test2()).start();
}
#Override
public void run() {
new Sample().a("call from main");
}
}
Test2 class
public class Test2 implements Runnable {
#Override
public void run() {
new Sample().b("call from main");
}
}
I just did this because I thought there will be a dead lock scenario if same thread witch holding the lock is going to access another method witch locked using same lock. Now consider the out put
call from main method a
call from main method b
inside synchronized block in a
waiting in a
calling b() from a // i thought this will cause a dead lock
call from a method b
bbb call from a
waiting again in a
Running again a
bbb call from main
Now you can see there is no such issue. My question is how Java manage this situation?
synchronized block is Reentrant
By default the lock (mutex to be precise) used in synchronized block is Reentrant, which means if the same thread tries to acquire the same lock again it will not have to wait and will immediately enter the critical block as it already owns that lock.
Where is Reentrancy useful?
Simple answer is Recursion.
Consider the scenario of recursion on a synchronized method,
int synchronized method(int param){
//... some logic
method(param - 1);
}
In this example you would not want the same thread to be blocked for the same lock, as it will never be able to proceed.
Deadlock occurs in this scenario:
Thread A acquires lock A
Thread B acquires lock B
Thread A tries to acquire lock B
Thread B tries to acquire lock A
Now in this situation no one will be able to proceed and hence deadlock. But in your scenario there is only one lock, so the other thread will just wait for the first thread to leave the lock and then continue.
Since your lock object is static it is shared among threads. Once thread A has acquired the lock, and when thread B enters method B of sample class it tries to acquire the same lock Which is owned by thread A. So there is no chance of deadlock.
Problem could have been where thread A tries to acuire the lock it already holds in method B, but this hasnt happened in your case as synchnorized block itself is reenterant but if you would have implemented your own lock class and if you wouldnt have cjecked for renterency, there would have been a dead lock.

If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method

In Java, if a synchronized method contains a call to a non-synchronized, can another method still access the non-synchronized method at the same time? Basically what I'm asking is everything in the synchronized method have a lock on it (including calls to other synchronized methods)?
If a synchronized method calls another non-synchronized method, is there a lock on the non-synchronized method
The answer depends on the context.
If you are in a synchronized method for an object, then calls by other threads to other methods of the same object instance that are also synchronized are locked. However calls by other threads to non-synchronized methods are not locked – anyone can call them at the same time.
public synchronized void someSynchronizedMethod() {
...
someNonSynchronizedMethod();
...
}
// anyone can call this method even if the someSynchronizedMethod() method has
// been called and the lock has been locked
public void someNonSynchronizedMethod() {
...
}
Also, if you call someSynchronizedMethod() but happen to be within the someNonSynchronizedMethod() method, you still hold the lock. The lock is enabled when you enter a synchronized method (or block) and is disabled when you exit that method. You can call all sorts of other unsynchronized methods and they will still be locked.
But you are asking two different things in your question:
In Java, if a synchronized method contains a call to a non-synchronized, can another method still access the non-synchronized method at the same time?
Yes. Other methods can access non-synchronized methods.
Basically what I'm asking is everything in the synchronized method have a lock on it (including calls to other synchronized methods)?
Uh, yes. Other calls to synchronized methods are locked. But non-synchronized methods are not locked.
Also, remember that if the method is static then the lock is on the Class object in the ClassLoader.
// this locks on the Class object in the ClassLoader
public static synchronized void someStaticMethod() {
If the method is an instance method then the lock is on the instance of the class.
// this locks on the instance object that contains the method
public synchronized void someInstanceMethod() {
There are 2 different locks in those 2 cases.
Lastly, when you are dealing with synchronized instance methods, each instance of the class is what is locked. This means that two threads could be in the same synchronized method at the same time with different instances. But if 2 threads try to operate on synchronized methods on the same instance, one will block until the other one exits the method.
If thread A calls synchronized method M1 which in turn calls unsynchronized method M2, then thread B can still call M2 without blocking.
Synchronized method acquires and releases intrinsic lock on the object on which it is called. This is why it may block. Unsynchronized method doesn't attempt to acquire any lock (unless it is done explicitly in the code).
Thus, if you need to ensure mutual exclusion for M2 as well, you should make it synchronized regardless of whether its callers (like M1) are synchronized or not.
The lock doesn't belong to the thread. The lock actually belongs to the object(or Class in case of Class level lock), and a thread acquires lock on the Object(or Class in case of Class level lock) within a synchronized context.
Now, there is no lock propagation in java as it is discussed above. Here is a small demo:
public class TestThread {
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ThreadCreator1 threadCreator1 = new ThreadCreator1();
ThreadCreator2 threadCreator2 = new ThreadCreator2();
Thread t1 = new Thread(threadCreator1,"Thread 1");
Thread t3 = new Thread(threadCreator1,"Thread 3");
Thread t2 = new Thread(threadCreator2,"Thread 2");
t1.start();
Thread.sleep(2000);
t3.start();
}
}
public class ThreadCreator1 implements Runnable {
private static final Task task= new Task();
private static final Task2 task2= new Task2();
#Override
public void run() {
try {
if(Thread.currentThread().getName().equals("Thread 1"))
task.startTask2(task2);
if(Thread.currentThread().getName().equals("Thread 3"))
task2.startTask();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
/**/
}
}
public class Task {
public static final Task task = new Task();
public static List<String> dataList = new ArrayList<String>();
ReentrantLock lock = new ReentrantLock();
public void startTask2(Task2 task2) throws InterruptedException
{
try{
lock.lock();
//new Task2().startTask();
task2.startTask();
}
catch(Exception e)
{
}
finally{
lock.unlock();
}
}
}
public class Task2 {
ReentrantLock lock = new ReentrantLock();
public void startTask() throws InterruptedException
{
try{
//lock.lock();
for(int i =0 ;i< 10;i++)
{
System.out.println(" *** Printing i:"+i+" for:"+Thread.currentThread().getName());
Thread.sleep(1000);
}
}
catch(Exception e)
{
}
/*finally
{
lock.unlock();
}*/
}
}
Just I have used Reentrant lock here.
If the above code is run, then there will be interleaving between thread 1 and thread 3, but if the lock portion of Task2 class is uncommented, then there will be no interleaving and the thread which acquire the lock first will complete fully first, then it will release the lock and then the other thread can carry on.
The lock belongs to the thread, not to the method (or more precisely, its stack frame). It just so happens that if you have a synchronized method, you're guaranteed that the thread will own the lock before the body of the method start, and will release it afterwards.
Another thread can still invoke the second, non-synchronized method. An unsynchronized method can be called by any thread at any time.

Categories