Concurrent Programming Fundamentals — Sharing Objects (Part 1)

In order to ensure visibility of memory writes across threads, synchronization is needed.

Locking is not just about mutual exclusion, it is also about memory visi-
bility. To assure that all threads can see the most up-to-date values of shared
mutable variables, the reading and writing threads must synchronize on
a common lock.

public class SharedNumber {

public int numberCounter = 0;

}
public class SharedNumber {

public volatile int numberCounter = 0;

}

Full volatile Visibility Guarantee

public class MyClass {
private int years;
private int months
private volatile int days;
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}
public class MyClass {
private int years;
private int months
private volatile int days;
public int totalDays() {
int total = this.days;
total += months * 30;
total += years * 365;
return total;
}
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}

Instruction Reordering Challenges

int a = 1;
int b = 2;
a++;
b++;
'
int a = 1;
a++;
int b = 2;
b++;
public class MyClass {
private int years;
private int months
private volatile int days;
public void update(int years, int months, int days){
this.years = years;
this.months = months;
this.days = days;
}
}
public void update(int years, int months, int days){
this.days = days;
this.months = months;
this.years = years;
}

The Java volatile Happens-Before Guarantee

volatile is Not Always Enough

When is volatile Enough?

Performance Considerations of volatile

Difference between synchronization and volatile keyword

Referred from javapoint

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store