diff --git a/pp.A4-HandOverHandLocking/src/main/java/pp/ThreadsafeSimplifiedList.java b/pp.A4-HandOverHandLocking/src/main/java/pp/ThreadsafeSimplifiedList.java index 8957eb5..ad7b277 100644 --- a/pp.A4-HandOverHandLocking/src/main/java/pp/ThreadsafeSimplifiedList.java +++ b/pp.A4-HandOverHandLocking/src/main/java/pp/ThreadsafeSimplifiedList.java @@ -2,6 +2,7 @@ package pp; public class ThreadsafeSimplifiedList implements SimplifiedList { private Node first; + private final Object headLock = new Object(); private static class Node { U element; @@ -22,37 +23,33 @@ public class ThreadsafeSimplifiedList implements SimplifiedList { @Override public boolean add(T element) { - synchronized (this) { + Node curr; + + synchronized (headLock) { if (first == null) { first = new Node<>(element, null, null); return true; } + curr = first; } - Node curr; - synchronized (first.lock) { - curr = first; - while (true) { - Node next; - synchronized (curr.lock) { - next = curr.next; - if (next == null) { - // letztes Element erreicht → neues anhängen - curr.next = new Node<>(element, curr, null); - return true; - } - } - synchronized (next.lock) { - curr = next; + while (true) { + Node 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 curr; - synchronized (this) { + synchronized (headLock) { if (first == null) throw new IndexOutOfBoundsException(); curr = first; } @@ -72,7 +69,7 @@ public class ThreadsafeSimplifiedList implements SimplifiedList { @Override public T set(int index, T element) { Node curr; - synchronized (this) { + synchronized (headLock) { if (first == null) throw new IndexOutOfBoundsException(); curr = first; } @@ -93,7 +90,7 @@ public class ThreadsafeSimplifiedList implements SimplifiedList { @Override public boolean isEmpty() { - synchronized (this) { + synchronized (headLock) { return first == null; } }