Week 3 - Synchronisation Flashcards
(10 cards)
what is a critical section
A sequence of instructions that only one thread should be able to access at a time otherwise it leads to unpredicatble outcomes
what is a lock
lock is a construct that declares a critical section indicating one thread access only at a time. just before a thread about to access crtifical section it checks if lock is free :
if successful it aqquires lock and releases the lock when it exits the critical section
if failure its blocked indefinitely until the lock is released
intrinsic lock
locks on entire instance of an object
Locks entire instance not just method
- If one thread gets the lock on that particular instance no other synchronised method can be used on that object
why are synchronised blocks good
So yes — synchronized blocks are more precise. They let you lock exactly what you need, and release the lock as early as possible, improving concurrency.
READ VERY IMPORTANT
speed wise
cpu -> cache -> RAM (fastest ->slowest)
cache holds frequently accessed data
ram is slow and holds important stuff like heap and data ( objects are instance variables stored here)
lets say on a multi core system ( share main memory , but have their own caches and cpu)
They each cacche frequently accessed data (objects and instance variables)
when one thread modifies an instance variable not immediately propagated to main memoryu (also it may read values from cache which could be out of data) this means lets say another thread reads that instance variable it hasnt received the update and so when modifying it would mofify wrong value (lost update)
leads to race conditions (from an architectural sense)
volatile introduction
youre an idiot if you dont read this crucial
To deal with issue we discussed previously (variables cached locally by each thread causing inconsistency , us not writing to main memory straight away , reading from cache with old values) we use the volatile keyword
volatile
when changed its straight away flushed to main memory
when accessed its only accessed from main memory NOT CACHE AS THIS MAY HAVE OLD VALUES
volatile visibility guarantee
if a variable marked as volatile to ram flushed then all other variables flushed
why is instruction reordering disasterous
hint think about volatile
so essentially jvm can choose to reorder lines in program for efficiency but this may be disasterous in volatile cases as a thread may read a value before another thread has actually modified it
so what volatile ensures is
anything before a volatile write must remain there ( so no unintended consequences)
anything after volatile write must remain there
excellent example:
✅ What volatile guarantees
When you do:
buffer.add(…); // Step 1
newDataAvailable = true; // Step 2 (volatile write)
The JVM guarantees:
Nothing before the volatile write (like the buffer update) can be moved after it
Nothing after can be moved before it either