BAEL-4499 - Synchronization bad practice and solution example

This commit is contained in:
Anshul BANSAL 2021-01-25 12:29:01 +02:00
parent de4c624e7e
commit 431442e3ca
4 changed files with 158 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalBadPractice {
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public synchronized void setName(String name) {
this.name = name;
}
public void setOwner(String owner) {
synchronized(this) {
this.owner = owner;
}
}
public AnimalBadPractice() {
}
public AnimalBadPractice(String name, String owner) {
this.name = name;
this.owner = owner;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.synchronizationbadpractices;
public class AnimalSolution {
private final Object objLock1 = new Object();
private final Object objLock2 = new Object();
private String name;
private String owner;
public String getName() {
return name;
}
public String getOwner() {
return owner;
}
public void setName(String name) {
synchronized(objLock1) {
this.name = name;
}
}
public void setOwner(String owner) {
synchronized(objLock2) {
this.owner = owner;
}
}
public AnimalSolution() {
}
public AnimalSolution(String name, String owner) {
this.name = name;
this.owner = owner;
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationBadPracticeExample {
public void stringBadPractice1() {
String stringLock = "LOCK_STRING";
synchronized (stringLock) {
// ...
}
}
private final String stringLock = "LOCK_STRING";
public void stringBadPractice2() {
synchronized (stringLock) {
// ...
}
}
private final String internedStringLock = new String("LOCK_STRING").intern();
public void stringBadPractice3() {
synchronized (internedStringLock) {
// ...
}
}
private final Boolean booleanLock = Boolean.FALSE;
public void booleanBadPractice() {
synchronized (booleanLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = count;
public void boxedPrimitiveBadPractice() {
synchronized (intLock) {
count++;
// ...
}
}
public void classBadPractice() throws InterruptedException {
AnimalBadPractice animalObj = new AnimalBadPractice("Tommy", "John");
synchronized(animalObj) {
while (true) {
Thread.sleep(Integer.MAX_VALUE);
}
}
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.synchronizationbadpractices;
public class SynchronizationSolutionExample {
private final String stringLock = new String("LOCK_STRING");
public void stringSolution() {
synchronized (stringLock) {
// ...
}
}
private int count = 0;
private final Integer intLock = new Integer(count);
public void boxedPrimitiveSolution() {
synchronized(intLock) {
count++;
// ...
}
}
private static int staticCount = 0;
private static final Object staticObjLock = new Object();
public void staticVariableSolution() {
synchronized(staticObjLock) {
staticCount++;
// ...
}
}
}