I’m trying to do a very special sorting into a LinkedList. I use a ListIterator to find the place where I want to add an item and that works quiet well. Only problem is that I have multiple threads that want to add and sort items. The adding itself is synchronized but a LinkedList uses non volatile properties. That isn’t safe, is it? Here is what I’m trying to do (simplified):
public class Test {
private LinkedList<Long> list = new LinkedList<Long>();
synchronized void add ( final long number ) {
// iterate our sorting list
final ListIterator<Long> iterator = list.listIterator( list.size() );
while (iterator.hasPrevious()) {
long current = iterator.previous();
if (current < number) {
if (iteratot.nextIndex() >= list.size()) {
list.add( number ); // I don't need the iterator anymore
} else {
iterator.next();
iterator.add( number );
}
}
// This here gets difficult
// I need the current number here! (which is the one that is a little lower than the added one)
}
}
}
The source above only resembles what I’m doing and is much more simple that the original.
Is there another List type I haven’t seen which is thread safe or another solution which I just don’t know about?
As long as the only way to access and modify
Test.listis throughTest.add(), your code is thread safe.If there are other ways to access/modify
Test.list, you need to tell us more.