Return to site

☕🎓JAVA CERTIFICATION QUESTION: synchronized and locks

· java,ocp

Given:

How do you make c1 and c2 incrementing atomic?

* set inc1() and inc2() as synchronized

* set inc1() synchronized while inc2() stays the same

* wrap the body of inc1() and inc2() in a synchronized block with the same lock

* wrap the body of inc1() and inc2() in a synchronized block with different lock

 

#java #certificationquestion #ocp

Answer: wrap the body of inc1() and inc2() in a synchronized block with different lock

Synchronized statements are useful for improving concurrency with fine-grained synchronization.

Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together.

All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2

— and doing so reduces concurrency by creating unnecessary blocking.

Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

See:

Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access to the affected fields.

https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html