Disclaimer: Dieser Thread wurde aus dem alten Forum importiert. Daher werden eventuell nicht alle Formatierungen richtig angezeigt. Der ursprüngliche Thread beginnt im zweiten Post dieses Threads.
LinkedList Blatt 4
Hier mal mein Versuch das ganze besser zu synchronisieren, was wäre da noch drin gewesen?
import java.util.*;
public class LinkedList<Type> {
private static class Item<Type> {
Item<Type> next;
Item<Type> prev;
final Type value;
Item(Type value) {
this.value = value;
}
}
/** Monitor object to synchronize the list */
private final Object monitor = new Object();
/**
* Head pointer of the list
* <code>next</code> points to the first and
* <code>prev</code> to the last element of the list
*/
private final Item<Type> head;
/** Number of inserted elements */
private AtomicInteger size;
/**
* creates an empty list
*/
public LinkedList() {
synchronized (monitor) {
head = new Item<Type>(null);
head.next = head.prev = head;
size.set(0);
}
}
/**
* Appends the given value at the end of the list
*
* @param value
*/
public void add(Type value) {
final Item<Type> n = new Item<Type>(value);
synchronized (monitor) {
n.next = head;
n.prev = head.prev;
n.next.prev = n.prev.next = n;
size.incrementAndGet();
}
}
/**
* @return Number of inserted elements
*/
public int size() {
return size.get();
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append('[');
int c = 1;
synchronized (monitor) {
if (head.next == head)
return "[]";
b.append(head.next.value);
for (Item<Type> ack = head.next.next; ack != head; ack = ack.next) {
if ((c++) % 10 == 0)
b.append('\n');
b.append(", " + ack.value);
}
}
b.append(']');
return b.toString();
}
}