Java static block thread safety
Java static block thread safety
Java static block thread safety
I ran into this when debugging a subtle initialisation issue in a multi-threaded application. Java guarantees that static blocks run exactly once, and that initialisation is thread-safe — subsequent threads will simply see the already-initialised value. This is actually one of the cleanest ways to do lazy initialisation without explicit synchronisation.
Watch How to create deadlock using static final variables on YouTube
How to create deadlock using static final variables in java
Link URL : https://youtu.be/p0HNCppq80A
- Static class initialization is guaranteed to be thread-safe by Java.
1
2
3
4
5
public class ClassUsedByThread {
static {
private final String FIRST = "first";
}
}
The above code static block will only run once for first calling thread.
The other threads will skip this since it is already initialized.
This post is licensed under
CC BY 4.0
by the author.