In the following example
Here is the sample code illustrating my questions:
BadDesign.java
public final class BadDesign{
private static int sensitiveData;
public synchronized static void changeDataViaStaticMethod(int a){
//... updating the sensitiveData
sensitiveData = a;
}
public synchronized void changeDataViaNonStaticMethod(int b){
//... updating the sensitiveData
sensitiveData = b;
}
public static void showSensitiveDataStatic(){
System.out.println("Static: " + Thread.currentThread().getName()+ " - " + sensitiveData);
}
public void showSensitiveData(){
System.out.println(Thread.currentThread().getName() + " - " + sensitiveData);
}
public static void main(String[] args){
new Thread(new TestThread11()).start();
new Thread(new TestThread11()).start();
}
}
And TestThread11.java
class TestThread11 implements Runnable{
public void run(){
int i = 0;
do{
BadDesign.changeDataViaStaticMethod(5);
BadDesign.showSensitiveDataStatic();
//... new object for every iteration
//... so synchronization of non-static method
//... doesn't really do anything significant here
BadDesign bd = new BadDesign();
bd.changeDataViaNonStaticMethod(10);
bd.showSensitiveData();
}while (i++ < 100);
}
}
The non-static version will allow two different threads to come in via different objects, acquire different locks and still access the same shared data. Fundamentally, that's not thread-safe, and basically makes the locks useless. You want any piece of shared data to be covered by one lock.
You can still use non-static methods if you really want to (e.g. if the result should be determined partly by instance data as well) but you should access the shared data via a shared lock, e.g.
private static final Object staticLock = new Object();
...
synchronized (staticLock)
{
// Read or write static data
}
There is no problem with the do-while loop, as
BadDesign.changeDataViaStaticMethod(5); //needs BadDesign Class lock.
BadDesign.showSensitiveDataStatic(); //does not need any lock
and
bd.changeDataViaNonStaticMethod(10); // needs lock for bd object.
bd.showSensitiveData(); //does not need any lock
I hope that answers your questions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With