Lazy synchronization, Optimistic synchronization Flashcards
What is the main idea behind lazy synchronization?
Postpone hard work
split 2 removal phases:
logical removal (mark component to be deleted)
physical removal(Do what needs to be done)
what call are most likely to be made in Lazy:
contains()
how does lazy refine optimistic sync
contains() are wait-free and add + remove traverse list only once in absence of contention
What does each node have extra in lazy?
boolean field called marked which indicates whether the node is reachable. Every unmarked node is reachable
Does the contains() every lock in lazy?
No
Does validation require to traverse through the list to determine if a node is reachable?
No
How does the validate function look in lazy()
private boolean
validate(Node pred, Node curr) {
return
!pred.marked &&
!curr.marked &&
pred.next == curr);
}
How does the contains method look for lazy?
public boolean contains(Item item) {
int key = item.hashCode();
Node curr = this.head;
while (curr.key < key) {
curr = curr.next;
}
return curr.key == key && !curr.marked;
}
how does the add method look for lazy?
same as optimistic
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();
}}}
How does remove look for Lazy?
public boolean remove(T item) {
int key = item.hashCode();
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) {
if (curr.key == key) {
curr.marked = true;
pred.next = curr.next;
return true;
} else {
return false;
}}} finally {
pred.unlock();
curr.unlock();
}}}
how does the contains method look for optimistic sync?
public boolean contains(T item) {
int key = item.hashCode();
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();
}
Good + bad about Optimistic sync:
Good: less lock get/release = better performance + concurrency
bad: need to traverse list twice + contains still acquires locks