Why intrinsic lock object do not require special treatment (static, final, volatile)? - java

In this oracle example of intrinsic locks and many more, the monitor object is never declared as volatile, final or nor it has any distinction from any other regular object
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
There are plenty of questions that debate volatile versus synchronization blocks
volatile fields and synchronized blocks,
difference between volatile and synchronized in java
when to use volatile vs synchronization in multithreading in java,
do you ever use the volatile keyword in java
and immutable objects
what are immutable objects,
immutability and synchronization in java
immutable objects java concurreny)in multithreading.
As a side note, I understand this subtle difference between declaring an object final versus immutability why-can-final-object-be-modified and why declaring the lock object as final would not make it immutable.
However, we have the famous pattern of the singleton class lazy initialization where the use of the volatile variables is essential.
public class SingletonDemo {
private static volatile SingletonDemo instance;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null ) {
synchronized (SingletonDemo.class) {
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
which in the above code example uses the Class object as lock.
Since for an object which is accessed by multiple threads you need to use some mechanism as above to ensure atomic access, why is that for intrinsic lock object there is no need for any special treatment?

These locks don't need special treatment because the MsLunch object itself needs to be published before it can be seen by any additional threads.
public class MyMain {
public static void main(String... args) {
MsLunch lunch = new MsLunch();
// ...
This is thread safe because local variables ("lunch") are not visible to more than one thread.
Next the class below makes the local reference visible to all threads in the system. When that happens we need to use volatile. The volatile keyword effectively creates a memory barrier that publish the object safely. This includes all writes made before the assignement including writes made internally when constructing the object.
C.f. Safe Publication
public class MyMain {
public static volatile MsLunch publicLunch;
public static void main(String... args) {
MsLunch lunch = new MsLunch();
publicLunch = lunch;
//...
}
}

It probably should be final. But final isn't anything really special- its only required in one special case (referencing a variable declared inside a function into an anonymous class). Any other case final is simply a reminder for the programmer to not overwrite the variable- you can remove every other use of the word final in your program and it will work perfectly. You're right, a programmer could assign to it and then cause problems. But if he doesn't, there's no issue. So go ahead and use final when you create one, but it isn't necessary for the program to compile.
As for static- depends on the usecase. Do you want to monitor all instances of a class, or each instance independently? In the first case, you use static in the second case you don't.
Volatile isn't needed because the object isn't actually being changed by the multiple threads. Its being synchronized on. This is completely different, and an older part of the Java language than volatile. There's no need to make the variable volatile as you won't be altering it, and the internal data structures used to monitor on an object already know they need to be thread safe (and in a stronger manner than volatile promises).

In this oracle example of intrinsic locks and many more, the monitor object is never declared as volatile, final or nor it has any distinction from any other regular object.
That's not true. See below.
Since for an object which is accessed by multiple threads you need to use some mechanism as above to ensure atomic access, why is that for intrinsic lock object there is no need for any special treatment?
It does have special treatment. It is synchronised on.

Related

Java "static final" vs just "static" variable while locking

I have been reading about using static objects as locks and the most common example would be something like this:
public class MyClass1 {
private static final Object lock = new Object();
public MyClass1() {
//unsync
synchronized(lock) {
//sync
}
//unsync
}
}
My question is does lock have to be final? I understand it is good to put it as final to assure that nobody messes with the value, but will it work without final?
Sure, it will work -- until you re-assign it. If lock is not final, somebody could assign another value to it (lock = new Object()). It's like replacing the locks in your door: if you still have the old keys, you won't be able to use the lock anymore.
Making lock final will prevent that from happening, so it's always a good idea to do it.
If you do not make the variable final, you may get a NullPointerException in the constructor of MyClass1 if you create the instance of MyClass1 in a different thread than the thread in which MyClass1 was loaded.
The final modifier guarantees safe publication of the lock in a way that not having final does not.
Also, if it's not final, it could be changed, leading to you locking on the wrong object instance.
You can find out more about the guarantees that the final modifier provides in terms of safe publication in the Java Language Specification Section 17.5 ("Final Field semantics"), which is in chapter 17 ("Threads and Locks").
Basically you have to make sure that once the lock object is created nobody messes up with it by any means. Hence, you have to make it constant which we do by using static final. So, by creating a constant we are making sure that our lock object is created as soon as the class is loaded and never modify that in application lifetime.
Bonus:
Another way of doing same is by using static initializer. This is well suited in the cases where you wish to do the lock object assignment in more than one statements. An example of same below:
public class Test {
private static final Test lockObject;
static {
System.out.println("Hello");
lockObject = new Test();
}
public static void main(String[] args) {
synchronized (lockObject) {
//your code goes here
}
}
}
Maybe it's more intuitive if written in a different way: it's pretty much the same as this
public class MyClass {
static Lock myLock = new ReentrantLock();
public MyClass1() {
//unsync
myLock.lock();
//sync
myLock.unlock();
//unsync
}
}
with the same consequences of myLock being final or not.
If it's not final and gets reassigned, the lock status will be irrelevant.
I'd recommend using the Lock class anyway.

How to make a class with static members and function thread safe?

I have a class defined as:
class Artifacts {
private static boolean isThreadStarted = false;
private SomeClass someClass;
public static void startThread() {
isThreadStarted = true;
}
public static void setSomeClass(SomeClass = someClass1) {
if(isThreadStarted) {
someClass = someClass1;
}
}
public static SomeClass getSomeClass() {
return someClass;
}
}
Now the use case is that a method will make the value of isThreadStarted to be true. After that, a thread will start and using the value of someClass.There can be multiple threads setting and getting the value of someClass. I want to make this thread safe.
There is an annotation #ThreadSafe and there is a function synchronized static which I guess will do the thing. Please help in deciding the right approach.
Two simple improvements you can make to make this class more threadsafe for the intended purpose are to make the someClass field volatile, and to use AtomicBoolean for the isThreadStarted field.
class Artifacts {
private static AtomicBoolean isThreadStarted = new AtomicBoolean(false);
private volatile SomeClass someClass;
The volatile will ensure that any other thread that has a reference to an Artifact instance, does not cache the someClass instance. The JVM will always retrieve the someClass field from one main source. If volatile is not used, then other threads may cache someClass and changes it it may not be reflected across all the threads that are using it.
AtomicBoolean gives you volatile feature plus atomic operations, like check and set in the same operation. Here is a excerpt from the Javadoc.
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
So, your main concern is that multiple threads will read and write the someClass field (and maybe the isThreadStarted field, as well).
I don't know what the #ThreadSafe annotation does, it's not part of Java Standard Edition 8.
The basic way to make that thread-safe is to use the synchronized keyword. Typically, you'd encapsulate access to your field in getter and setter methods and make them synchronized.
public class Test {
private String someText;
public synchronized String getSomeText() {
return someText;
}
public synchronized void setSomeText(String someText) {
this.someText = someText;
}
}
But typically the multi-thread problems aren't tied to a single field.
If different threads of your program use a (thread-shared) object, you run into the risk that one thread modifies two fields A and B (e.g. moves money from A to B by subtracting from A and adding to B), and in-between some other thread reads A and B (e.g. calculates the current amount of A plus B) and sees an inconsistent state (amount subtracted from A, but not yet added to B).
The classical solution is to ensure that of all these code sections where the instance is read or modified, only one at a time is allowed to run. And that's what synchronized does.
Life_Hacker,
1st way
use static synchronized keyword with function to make Class Level lock in multithreading environment.
example :
public static synchronized void setSomeClass(Artifacts.class) {
if(isThreadStarted) {
someClass = someClass1;
}
}
2nd way
inside function definition, you can create Synchronize Block
example:
public static void setSomeClass(SomeClass = someClass1) {
synchronized(this){
if(isThreadStarted) {
someClass = someClass1;
}
}
}
2nd way is best approach

What's the difference between a singleton Class with synchronized function and a static synchronized function

I have less experience of multi-thread programming. I have multi-threads to write to a file. And I was wondering what's the difference between:
Implement 1: a class with static synchronized function. And each thread call FileUtil.writeToFile()
public class FileUtil {
public static synchronized void writeToFile(String filename) {
// write to file....
}
}
Implement 2: A singleton class. And each thread call Fileutil.getInstance().writeToFile()
public class FileUtil {
private static final FileUtil fileManager = new FileUtil();
private FileUtil() {
}
public synchronized void writeToFile(String filename) {
// write to file....
}
public static FileUtil getInstance() {
return fileManager;
}
}
There is no practical difference.
In practice, either way, you have one unique lock object that all callers must acquire in order to enter the method.
The only difference is the identity of the lock object: In the singleton case, the lock object is the singleton. In the static method case, it's the Class object.
The issues in your question can be divided into:
Should I use a class with static methods or the singleton pattern? This has already been discussed, for example in Difference between static class and singleton pattern?.
Is there a difference between the two synchronizations? Well, one locks on a class, the other on an object. And as Sotirios Delimanolis linked in the comments, it's discussed in Java synchronized static methods: lock on object or class.
Regarding the choice of monitor, there is a third option:
Use a monitor object that is not accessible to the caller. The advantage of this is that if the user of the class or the singleton decides to use that class or that singleton as a monitor in his own program, it won't cause all calls to writeToFile() to be blocked.
That is, suppose somebody does this:
FileUtil obj = FileUtil.getInstance();
synchronized ( obj ) {
// Some long operation
}
Because the writeToFile() method synchronizes on that same instance, no other thread will be able to use writeToFile() until the "long operation" is done and the synchronized block is left.
Now, instead, if you did this:
public class FileUtil {
private static final FileUtil fileManager = new FileUtil();
private static final Object lock = new Object(); // To be used for synchronizing
private FileUtil() {
}
public void writeToFile(String filename) {
synchronized (lock) {
// write to file....
}
}
public static FileUtil getInstance() {
return fileManager;
}
}
then even if the user of your class decides to use it as a lock (be it the class monitor or an instance monitor), it's not going to interfere with the functionality of writeToFile().
In short, there is no real difference.
The thing to note here is that in synchronization number 1 (static synchronized method), all threads would compete on acquiring the lock on the Class object (that represents the FileUtil class) and only one thread will acquire the lock at a time and execute the method.
In the second case all threads would again compete on acquiring the monitor associated with the "this" object (and only one thread will acquire it and execute at a time). Note we are talking about a singleton so there is exactly one instance in this address space (there could be more than one instance if this class is loaded through more than one classloaders as well but we digress).
In either case all the threads are competing to acquire a lock on exactly one object: the class description object or the "this" object and therefore there is no real difference when you run the program. There is a slight heap difference in that an instance of the FileUtil is created in the second case and put on the heap but that is inconsequential.
Both are equivalent in delivering the same result.
But I prefer second implementation of Singleton class + RealSkeptic suggestion to have static final lock object.
Advantage with Singleton : In future, you can change Singleton to ObjectPool of FileUtil with a certain size (e.g.: 5 objects of FileUtil). You have more control with pool of FileUtil with static Object lock compared to static synchronized method in first implementation.

Concurrency in Java: synchronized static methods

I want to understand how locking is done on static methods in Java.
let's say I have the following class:
class Foo {
private static int bar = 0;
public static synchronized void inc() { bar++; }
public synchronized int get() { return bar; }
It's my understanding that when I call f.get(), the thread acquires the lock on the object f and when I do Foo.inc() the thread acquires the lock on the class Foo.
My question is how are the two calls synchronized in respect to each other?
Is calling a static method also acquires a lock on all instantiations, or the other way around (which seems more reasonable)?
EDIT:
My question isn't exactly how static synchronized works, but how does static and non-static methods are synchronized with each other.
i.e., I don't want two threads to simultaneously call both f.get() and Foo.inc(), but these methods acquire different locks. My question is how is this preventable and is it prevented in the above code.
Static and instance synchronized methods are not related to each other, therefore you need to apply some additional synchronization between them, like this:
class Foo {
private static int bar = 0;
public static synchronized void inc() { bar++; }
public synchronized int get() {
synchronized (Foo.class) { // Synchronizes with static synchronized methods
return bar;
}
}
}
(though in this case leaving synchronized on get() doesn't make sense, since it doesn't do anything that requires synchronization on instance).
Beware of deadlocks - since this code aquires multiple locks, it should do it in consistent order, i.e. other synchronized static methods shouldn't try to acquire instance locks.
Also note that this particular task can be solved without synchronization at all, using atomic fields:
class Foo {
private static AtomicInteger bar = new AtomicInteger(0);
public static void inc() { bar.getAndIncrement(); }
public int get() { return bar.get(); }
}
A synchronized static method is effectively equivalent to:
public static void foo() {
synchronized (ClassName.class) {
// Body
}
}
In other words, it locks on the Class object associated with the class declaring the method.
From section 8.4.3.6 of the JLS:
A synchronized method acquires a monitor (ยง17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.
If you read http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html.
It will tell you:
You might wonder what happens when a
static synchronized method is invoked,
since a static method is associated
with a class, not an object. In this
case, the thread acquires the
intrinsic lock for the Class object
associated with the class. Thus access
to class's static fields is controlled
by a lock that's distinct from the
lock for any instance of the class.
which tells you all you need to know.
Neither, the non-static synchronized call does not acquire a lock on the class itself. (And the static synchronized block does not lock any object instantiated from that class.)
In other words the calls f.get() (locks f) and Foo.inc() (locks the class Foo) can run concurrently. They are not "synchronized".
You could use a different pattern (singleton), or make all the methods static.
Static locks are attached to the class definition and thus is shared between all instances of that class.
Synchronization of none static methods only apply to the current instance of the class (the lock is on the class instance, e.g., this). In your example you have two different locks with no interrelation.
I don't want two threads to simultaneously call both f.get() and Foo.inc(), but these methods acquire different locks. My question is how is this preventable and is it prevented in the above code
You must share a lock to be able to arbitrate access to both f.get and Foo.inc(). You can do this either by sharing the same static lock or by the same instance lock.
These two calls do not synchronize in respect to each other.
It is as you said, a caller of f.get() acquires the lock of f object and caller of Foo.inc() acquires Foo.class object's one. So the synchronization rules are the same as if instead of static call you called an instance synchronized method with another object.

How to lock a method for a whole class using synchronized?

I know when you want to lock method to be executed by only one thread you declare it with synchronized keyword.
What about classes, how to provide a lock on an entire class of objects when a thread
is executing some code on an instance of that class?
In other words, when a thread is executing a method on an object, no other thread should be
allowed to execute the same method even on a different instance of the same class.
You synchronize on a specific object, either some designated static lock object, or the class object (which happens when static methods are declared to be synchronized):
class X {
private static final Object lock = new Object();
public void oneAtATime() {
synchronized (lock) {
// Do stuff
}
}
}
class Y {
public void oneAtATime() {
synchronized (Y.class) {
// Do stuff
}
}
}
Each variant has its own pros and cons; locking on the class allows other code, outside of the class, to use the same lock for its own reasons (which allows it to orchestrate more high-level synchronization than what you provide) while the static final Object lock approach lets you prohibits it by making the lock field private (which makes it easier to reason about the locking and avoid your code from deadlocking because someone else wrote bad code).
You could of course also use some synchronization mechanism from java.util.concurrent, like explicit Locks, which provide more control over locking (and ReentrantLock currently performs a little better than implicit locks under high contention).
Edit: Note that static/global locks aren't a great way to go - it means every instance of the class ever created will essentially be tied to every other instance (which, aside from making it harder to test or read the code, can severely harm scalability). I assume you do this to synchronize some kind of global state? In that case, I'd consider wrapping that global/static state in a class instead, and implement synchronization per-instance rather than globally.
Instead of something like this:
class Z {
private static int state;
public void oneAtATime(){
synchronized (Z.class) {
state++;
}
}
}
Do it like this:
class State {
private int value;
public synchronized void mutate(){ value++; }
}
class Z {
private final State state;
public Z(State state){
this.state = state;
}
public void oneAtATime(){
state.mutate();
}
}
// Usage:
State s1 = new State(), s2 = new State();
Z foo = new Z(s1);
Z bar = new Z(s1);
Z frob = new Z(s2);
Z quux = new Z(s2);
Now foo and bar are still tied to each other, but they can work independently from frob and quux.
If you use static synchronized methods, they are locked via the Class Lock. You can also declare a static Object in the class and lock that in a method I believe via something like:
private static final Object STATIC_LOCK = new Object();
private void foo() {
synchronized (STATIC_LOCK) {
//do stuff...
}
}
You could use a static Mutex inside that method. So any concurrent thread is blocking inside the method while another is running it no matter what object of the class it belongs to. I don't think there is any special single keyword to produce the same effect like synchronized.
It is a rather aggressive synchronization, I would avoid it as much as possible.
Synchronize on static field of your class, or the class itself:
synchronized(MyClass.class) {
// mutually excluded method body
}
Both threads must use this construction
public void someMethod() {
synchronized(ClassThatShouldBeProtected.class) {
someSynchronizedCode();
}
}
This approach benefits from the fact, that class itself is an object and therefore it has a monitor. Then you don't need any artificial static instance.
There is no built-in mechanism for this. Create your own static lock attribute, and make sure you lock it and unlock it in every method. Don't forget about exceptions - make sure you unlock it in the "finally" sections.
This should work:
public class MyClass {
void synchronizedMethod() {
synchronized (MyClass.class) {
// synchronized on static level
}
}
}
Which 'missuses' the class's runtime-representation for locking. This is possible as any object can be used as a mutex in Java.
http://www.janeg.ca/scjp/threads/synchronization.html
talks about several ways to achieve it.
in general, locks are prohibitive and hinder benefits of threading. so the critical code should be minimized as much as its possible.
do you want a class lever lock to access static variables of the class or is it for protecting access to a common external resource the class? in which case you should proly have a separate lock while accessing it.

Categories