headLock has been added! v2

SL_U2_SJ
Shahnam Javidnia 2025-05-23 02:30:40 +02:00
parent c9b1dfbe48
commit 7093dea6fa
1 changed files with 16 additions and 18 deletions

View File

@ -2,6 +2,7 @@ package pp;
public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
private Node<T> first;
private final Object headLock = new Object();
private static class Node<U> {
U element;
@ -22,36 +23,33 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
@Override
public boolean add(T element) {
synchronized (this) {
Node<T> curr;
synchronized (headLock) {
if (first == null) {
first = new Node<>(element, null, null);
return true;
}
curr = first;
}
Node<T> curr;
synchronized (first.lock) {
curr = first;
while (true) {
Node<T> next;
synchronized (curr.lock) {
next = curr.next;
if (next == null) {
curr.next = new Node<>(element, curr, null);
return true;
}
}
synchronized (next.lock) {
curr = next;
while (true) {
Node<T> next;
synchronized (curr.lock) {
next = curr.next;
if (next == null) {
curr.next = new Node<>(element, curr, null);
return true;
}
}
curr = next;
}
}
@Override
public T get(int index) {
Node<T> curr;
synchronized (this) {
synchronized (headLock) {
if (first == null) throw new IndexOutOfBoundsException();
curr = first;
}
@ -71,7 +69,7 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
@Override
public T set(int index, T element) {
Node<T> curr;
synchronized (this) {
synchronized (headLock) {
if (first == null) throw new IndexOutOfBoundsException();
curr = first;
}
@ -92,7 +90,7 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
@Override
public boolean isEmpty() {
synchronized (this) {
synchronized (headLock) {
return first == null;
}
}