SlideShare a Scribd company logo
1 of 16
Advanced Locking Techniques
•
•
•
•

Coarse-grained Synchronization
Fine-grained Synchronization
Optimistic Synchronization
Lazy Synchronization
List-based Set
head

pred

curr

tail

c

a

b

head

pred
a

tail

curr
b

c

class node {
T item; int key; Node next;
}
Coarse-grained Synchronization
• Take a sequential implementation, add a lock
field, and ensure that each method call
acquires and releases this lock
• Simple, and works well when levels of
concurrency is low
• When too many threads try to access the
object at the same time, the object becomes a
sequential bottleneck
Coarse-grained Locking
public class CoarseList<T> {
private Node head;
private Lock lock = new ReentrantLock ();
public CoarseList () {
head = new Node (Integer.MIN_VALUE);
head.next = new Node (Integer.MAX_VALUE);
}
public boolean add (T item) {
Node pred, curr;
int key = item.hashCode ();
lock.lock ();
try {
pred = head;
curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;
}
if (key == curr.key) {
return false;
} else {
Node node = new Node (item);
node.next = curr; pred.next = node;
return true;
}
finally {
lock.unlock ();
}
}
}

public boolean remove (T item) {
Node pred, curr;
int key = item.hashCode ();
lock.lock ();
try {
pred = head;
curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;

}

}
if (key = curr.key) {
pred.next = curr.next;
return true;
} else {
return false;
}
} finally {
lock.unlock ();
}
Fine-grained Synchronization
• Improve concurrency by locking individual
nodes, instead of locking the entire list
• Operations interfere only when trying to
access the same node at the same time
• Higher concurrency, but requires a lock to be
added for each node
Fine-grained Locking
public class CoarseList<T> {
private Node head;
public CoarseList () {
head = new Node (Integer.MIN_VALUE);
head.next = new Node (Integer.MAX_VALUE);
}
public boolean add (T item) {
int key = item.hashCode ();
head.lock ();
Node pred = head;
try {
Node curr = pred.next;
curr.lock ();
try {
while (curr.key < key) {
pred.unlock();
pred = curr; curr = curr.next;
curr.lock ();
}
if (key == curr.key) {
return false;
}
Node newNode = new Node (item);
newNode.next = curr;
pred.next = newNode;
return true;
} finally {
curr.unlock ();
}
} finally {
pred.unlock ();
}
}

}

public boolean remove (T item) {
Node pred = null, curr = null;
int key = item.hashCode ();
head.lock ();
try {
pred = head;
curr = pred.next;
curr.lock();
try {
while (curr.key < key) {
pred.unlock ();
pred = curr; curr = curr.next;
curr.lock ();
}
if (key = curr.key) {
pred.next = curr.next;
return true;
}
return false;
} finally {
curr.unlock ();
}
} finally {
pred.unlock ();
}
}
Why Two Locks?
head

pred
a

Thread A

Thread B

tail

curr
b

c
Hand-Over-Hand Locking
head

pred
a

Thread A

tail

curr
b

c

Thread B

Except for the initial head node, acquire the lock for curr only
while holding the lock for pred
Optimistic Synchronization
• Search a component without acquiring any
locks
• When a node is found, it locks the
component, and then checks whether the
component has been changed
• Optimistic about the possibility of conflicting
Optimistic Locking (1)
public boolean add (T item) {
int key = item.hashCode ();
while (true) {
Node pred = head;
Node curr = pred.next;
while (curr.key <= key) {
pred = curr; curr = curr.next;
}
pred.lock(); curr.lock ();
try {
if (validate(pred, curr)) {
if (curr.key == key) {
return false;
} else {
Node node = new Node
(item);
node.next = curr; pred.next
= node;
return true;
}
}
} finally {
pred.unlock (); curr.unlock();
}
}
}

public boolean remove (T item) {
int key = item.hashCode ();
while (true) {
Node pred = head;
Node curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;
}
pred.lock(); curr.lock ();
try {
if (validate(pred, curr)) {
if (curr.key == key) {
pred.next = curr.next;
return true;
} else {
return flase;
}
}
} finally {
pred.unlock (); curr.unlock();
}
}
}
Optimistic Locking (2)
public boolean contains (T item) {
int key = item.hashCode ();
while (true) {
Node pred = head;
Node curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;
}
try {
pred.lock(); curr.lock ();
if (validate(pred, curr)) {
return (curr.key = key);
}
} finally {
pred.unlock (); curr.unlock();
}
}
}

public boolean validate (
Node pred, Node curr) {
Node node = head;
while (node.key <= pred.key) {
if (node == pred)
return pred.next = curr;
node = node.next;
}
return false;
}
Why validation?
head

pred

tail

curr
Lazy Synchronization
• Postpone significant changes, e.g., physically
removing a node from a linked list
• Allow a list to be traversed only once without
locking, and contains() is wait-free.
• Require a new field marked to be added into
each node
Lazy Locking (1)
public boolean add (T item) {
int key = item.hashCode ();
while (true) {
Node pred = head;
Node curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;
}
pred.lock();
try {
curr.lock();
try {
if (validate(pred, curr)) {
if (curr.key == key) {
return false;
} else {
Node node = new Node
(item);
node.next = curr;
pred.next = node;
return true;
}
}
} finally {
curr.unlock();
}
} finally {
pred.unlock ();
}
}
}

public boolean remove (T item) {
int key = item.hashCode ();
while (true) {
Node pred = head;
Node curr = pred.next;
while (curr.key < key) {
pred = curr; curr = curr.next;
}
pred.lock();
try {
curr.lock ();
try {
if (validate(pred, curr)) {
if (curr.key != key) {
return false;
} else {
curr.marked = true;
pred.next = curr.next;
return flase;
}
}
} finally {
curr.unlock ();
}
} finally {
pred.unlock ();
}
}
}
Lazy Locking (2)
public boolean contains (T item) {
int key = item.hashCode ();
Node curr = head;
while (curr.key < key) {
curr = curr.next;
}
return curr.key == key && !
curr.marked;
}

private boolean validate (Node pred,
Node curr) {
return !pred.marked && !curr.marked
&& pred.next = curr;
}
Can we do better?
• Non-blocking synchronization: eliminate locks
entirely, relying on built-in atomic operations
such as compareAndSet() for synchronization

More Related Content

What's hot

Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSSusan Potter
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in JavaDoug Hawkins
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesTeerawat Issariyakul
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginnersishan0019
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rustnikomatsakis
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareFastly
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting StartedTeerawat Issariyakul
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"OdessaJS Conf
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in JavaMisha Kozik
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Yandex
 
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...Alex Pruden
 

What's hot (20)

Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
From Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
 
Concurrency Concepts in Java
Concurrency Concepts in JavaConcurrency Concepts in Java
Concurrency Concepts in Java
 
NS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variablesNS2: Binding C++ and OTcl variables
NS2: Binding C++ and OTcl variables
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
RealmDB for Android
RealmDB for AndroidRealmDB for Android
RealmDB for Android
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
Pattern Matching in Java 14
Pattern Matching in Java 14Pattern Matching in Java 14
Pattern Matching in Java 14
 
分散式系統
分散式系統分散式系統
分散式系統
 
Nicety of Java 8 Multithreading
Nicety of Java 8 MultithreadingNicety of Java 8 Multithreading
Nicety of Java 8 Multithreading
 
Implementing STM in Java
Implementing STM in JavaImplementing STM in Java
Implementing STM in Java
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
zkStudyClub: PLONKUP & Reinforced Concrete [Luke Pearson, Joshua Fitzgerald, ...
 

Viewers also liked (7)

ABA Problem
ABA ProblemABA Problem
ABA Problem
 
Role of locking
Role of lockingRole of locking
Role of locking
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization
 
Linked lists
Linked listsLinked lists
Linked lists
 
Adsa u2 ver 1.0.
Adsa u2 ver 1.0.Adsa u2 ver 1.0.
Adsa u2 ver 1.0.
 
Ict u4
Ict u4Ict u4
Ict u4
 
Electronic code lock device
Electronic code lock deviceElectronic code lock device
Electronic code lock device
 

Similar to Advanced Locking Techniques: Coarse-grained, Fine-grained, Optimistic, Lazy

C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfC++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfarjuncp10
 
Lock free algorithms
Lock free algorithmsLock free algorithms
Lock free algorithmsPan Ip
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Explorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en RustExplorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en RustGermán Küber
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdfangelsfashion1
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresDilum Bandara
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)tarcieri
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queuesSSE_AndyLi
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Link list part 2
Link list part 2Link list part 2
Link list part 2Anaya Zafar
 
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfProblem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfmumnesh
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07DooSeon Choi
 

Similar to Advanced Locking Techniques: Coarse-grained, Fine-grained, Optimistic, Lazy (20)

Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdfC++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
C++Write a function void headEnqueue(Queue q, int key) which enqu.pdf
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Lock free algorithms
Lock free algorithmsLock free algorithms
Lock free algorithms
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Explorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en RustExplorando el Diseño de la Memoria en Rust
Explorando el Diseño de la Memoria en Rust
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data Structures
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues10 chapter6 heaps_priority_queues
10 chapter6 heaps_priority_queues
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Lua Study Share
Lua Study ShareLua Study Share
Lua Study Share
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Linked lists
Linked listsLinked lists
Linked lists
 
Lockless
LocklessLockless
Lockless
 
Link list part 2
Link list part 2Link list part 2
Link list part 2
 
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdfProblem 1 Create Node class (or use what you have done in Lab4)• .pdf
Problem 1 Create Node class (or use what you have done in Lab4)• .pdf
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07CppConcurrencyInAction - Chapter07
CppConcurrencyInAction - Chapter07
 

More from Dr. C.V. Suresh Babu (20)

Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
 
Association rules
Association rulesAssociation rules
Association rules
 
Clustering
ClusteringClustering
Clustering
 
Classification
ClassificationClassification
Classification
 
Blue property assumptions.
Blue property assumptions.Blue property assumptions.
Blue property assumptions.
 
Introduction to regression
Introduction to regressionIntroduction to regression
Introduction to regression
 
DART
DARTDART
DART
 
Mycin
MycinMycin
Mycin
 
Expert systems
Expert systemsExpert systems
Expert systems
 
Dempster shafer theory
Dempster shafer theoryDempster shafer theory
Dempster shafer theory
 
Bayes network
Bayes networkBayes network
Bayes network
 
Bayes' theorem
Bayes' theoremBayes' theorem
Bayes' theorem
 
Knowledge based agents
Knowledge based agentsKnowledge based agents
Knowledge based agents
 
Rule based system
Rule based systemRule based system
Rule based system
 
Formal Logic in AI
Formal Logic in AIFormal Logic in AI
Formal Logic in AI
 
Production based system
Production based systemProduction based system
Production based system
 
Game playing in AI
Game playing in AIGame playing in AI
Game playing in AI
 
Diagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AIDiagnosis test of diabetics and hypertension by AI
Diagnosis test of diabetics and hypertension by AI
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 
A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”A study on “impact of artificial intelligence in covid19 diagnosis”
A study on “impact of artificial intelligence in covid19 diagnosis”
 

Recently uploaded

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Advanced Locking Techniques: Coarse-grained, Fine-grained, Optimistic, Lazy

  • 1. Advanced Locking Techniques • • • • Coarse-grained Synchronization Fine-grained Synchronization Optimistic Synchronization Lazy Synchronization
  • 3. Coarse-grained Synchronization • Take a sequential implementation, add a lock field, and ensure that each method call acquires and releases this lock • Simple, and works well when levels of concurrency is low • When too many threads try to access the object at the same time, the object becomes a sequential bottleneck
  • 4. Coarse-grained Locking public class CoarseList<T> { private Node head; private Lock lock = new ReentrantLock (); public CoarseList () { head = new Node (Integer.MIN_VALUE); head.next = new Node (Integer.MAX_VALUE); } public boolean add (T item) { Node pred, curr; int key = item.hashCode (); lock.lock (); try { pred = head; curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } if (key == curr.key) { return false; } else { Node node = new Node (item); node.next = curr; pred.next = node; return true; } finally { lock.unlock (); } } } public boolean remove (T item) { Node pred, curr; int key = item.hashCode (); lock.lock (); try { pred = head; curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } } if (key = curr.key) { pred.next = curr.next; return true; } else { return false; } } finally { lock.unlock (); }
  • 5. Fine-grained Synchronization • Improve concurrency by locking individual nodes, instead of locking the entire list • Operations interfere only when trying to access the same node at the same time • Higher concurrency, but requires a lock to be added for each node
  • 6. Fine-grained Locking public class CoarseList<T> { private Node head; public CoarseList () { head = new Node (Integer.MIN_VALUE); head.next = new Node (Integer.MAX_VALUE); } public boolean add (T item) { int key = item.hashCode (); head.lock (); Node pred = head; try { Node curr = pred.next; curr.lock (); try { while (curr.key < key) { pred.unlock(); pred = curr; curr = curr.next; curr.lock (); } if (key == curr.key) { return false; } Node newNode = new Node (item); newNode.next = curr; pred.next = newNode; return true; } finally { curr.unlock (); } } finally { pred.unlock (); } } } public boolean remove (T item) { Node pred = null, curr = null; int key = item.hashCode (); head.lock (); try { pred = head; curr = pred.next; curr.lock(); try { while (curr.key < key) { pred.unlock (); pred = curr; curr = curr.next; curr.lock (); } if (key = curr.key) { pred.next = curr.next; return true; } return false; } finally { curr.unlock (); } } finally { pred.unlock (); } }
  • 7. Why Two Locks? head pred a Thread A Thread B tail curr b c
  • 8. Hand-Over-Hand Locking head pred a Thread A tail curr b c Thread B Except for the initial head node, acquire the lock for curr only while holding the lock for pred
  • 9. Optimistic Synchronization • Search a component without acquiring any locks • When a node is found, it locks the component, and then checks whether the component has been changed • Optimistic about the possibility of conflicting
  • 10. Optimistic Locking (1) public boolean add (T item) { int key = item.hashCode (); while (true) { Node pred = head; Node curr = pred.next; while (curr.key <= key) { pred = curr; curr = curr.next; } pred.lock(); curr.lock (); try { if (validate(pred, curr)) { if (curr.key == key) { return false; } else { Node node = new Node (item); node.next = curr; pred.next = node; return true; } } } finally { pred.unlock (); curr.unlock(); } } } public boolean remove (T item) { int key = item.hashCode (); while (true) { Node pred = head; Node curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } pred.lock(); curr.lock (); try { if (validate(pred, curr)) { if (curr.key == key) { pred.next = curr.next; return true; } else { return flase; } } } finally { pred.unlock (); curr.unlock(); } } }
  • 11. Optimistic Locking (2) public boolean contains (T item) { int key = item.hashCode (); while (true) { Node pred = head; Node curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } try { pred.lock(); curr.lock (); if (validate(pred, curr)) { return (curr.key = key); } } finally { pred.unlock (); curr.unlock(); } } } public boolean validate ( Node pred, Node curr) { Node node = head; while (node.key <= pred.key) { if (node == pred) return pred.next = curr; node = node.next; } return false; }
  • 13. Lazy Synchronization • Postpone significant changes, e.g., physically removing a node from a linked list • Allow a list to be traversed only once without locking, and contains() is wait-free. • Require a new field marked to be added into each node
  • 14. Lazy Locking (1) public boolean add (T item) { int key = item.hashCode (); while (true) { Node pred = head; Node curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } pred.lock(); try { curr.lock(); try { if (validate(pred, curr)) { if (curr.key == key) { return false; } else { Node node = new Node (item); node.next = curr; pred.next = node; return true; } } } finally { curr.unlock(); } } finally { pred.unlock (); } } } public boolean remove (T item) { int key = item.hashCode (); while (true) { Node pred = head; Node curr = pred.next; while (curr.key < key) { pred = curr; curr = curr.next; } pred.lock(); try { curr.lock (); try { if (validate(pred, curr)) { if (curr.key != key) { return false; } else { curr.marked = true; pred.next = curr.next; return flase; } } } finally { curr.unlock (); } } finally { pred.unlock (); } } }
  • 15. Lazy Locking (2) public boolean contains (T item) { int key = item.hashCode (); Node curr = head; while (curr.key < key) { curr = curr.next; } return curr.key == key && ! curr.marked; } private boolean validate (Node pred, Node curr) { return !pred.marked && !curr.marked && pred.next = curr; }
  • 16. Can we do better? • Non-blocking synchronization: eliminate locks entirely, relying on built-in atomic operations such as compareAndSet() for synchronization

Editor's Notes

  1. Nodes are sorted, so that it is quick to detect the absence of a node. We will assume the keys are unique.
  2. Use a single lock to manage all the synchronization operations.
  3. The problem is that there is no overlap between the locks held by the two remove() calls.
  4. This is because another thread could remove node b after you release pred but before you acquire curr.
  5. Problems with fine-grained locking: Still requires a lot of lock acquisitions and releases. Threads access disjoint items may still block each other, e.g., a thread removing the second item in the list blocks all concurrent threads searching for later nodes.
  6. Validation checks that pred is still reachable, and it still points to curr.
  7. It is possible that the trail of references leading to pred or the reference from pred to curr could have changed between when they were last read by a thread and when the thread acquires the locks (to perform the actual operation). Note that absence of interference implies that once a node has been unlinked from the list, the value of its next field does not change, so following a sequence of such links eventually leads back to the list.
  8. OptimisticLock works well if the cost of traversing the list twice without locking is significantly less than the cost of traversing the list once with locking. However, one drawback is that contains() are likely to be called very often, and it requires locks. Traversal does not require locking. Maintains the invariant that every unmarked node is reachable. Remove takes two steps: First, mark the target node, logically removing it, and second, redirect its predecessor’s next field, physically removing it.