Compare commits
No commits in common. "bde868ad4746fca3a867774a0bc5b2594b998c26" and "c9b1dfbe4879dbba9d6187284d4f2aaaaf463566" have entirely different histories.
bde868ad47
...
c9b1dfbe48
|
@ -2,7 +2,6 @@ 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;
|
||||
|
@ -23,33 +22,36 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
|
|||
|
||||
@Override
|
||||
public boolean add(T element) {
|
||||
Node<T> curr;
|
||||
|
||||
synchronized (headLock) {
|
||||
synchronized (this) {
|
||||
if (first == null) {
|
||||
first = new Node<>(element, null, null);
|
||||
return true;
|
||||
}
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
curr = next;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get(int index) {
|
||||
Node<T> curr;
|
||||
synchronized (headLock) {
|
||||
synchronized (this) {
|
||||
if (first == null) throw new IndexOutOfBoundsException();
|
||||
curr = first;
|
||||
}
|
||||
|
@ -69,7 +71,7 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
|
|||
@Override
|
||||
public T set(int index, T element) {
|
||||
Node<T> curr;
|
||||
synchronized (headLock) {
|
||||
synchronized (this) {
|
||||
if (first == null) throw new IndexOutOfBoundsException();
|
||||
curr = first;
|
||||
}
|
||||
|
@ -90,7 +92,7 @@ public class ThreadsafeSimplifiedList<T> implements SimplifiedList<T> {
|
|||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
synchronized (headLock) {
|
||||
synchronized (this) {
|
||||
return first == null;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue