Java Generics
Java Generics
Philip Wadler,
University of Edinburgh
TS-2890
Before:
List ints = Arrays.asList(1,2,3);
int s = 0;
for (Iterator it = ints.iterator(); it.hasNext();){
s += it.next();
}
After:
List<Integer> ints = Arrays.asList(1,2,3);
int s = 0;
for (int n : ints) { s += n; }
Trust Person
With erasure:
Generified Legacy
=
library binary library binary
Allows piecewise generification of libraries
Erasure Eases Evolution
2007 JavaOneSM Conference | Session TS-2890 | 10
From Legacy…
Library
interface Stack {
void push(Object elt);
Object pop();
}
class ArrayStack implements Stack {
private List li = new ArrayList();
public void push(Object elt) { li.add(elt); }
public Object pop(){ return li.remove(li.size()-1); }
}
Client
Stack stack = new ArrayStack();
stack.push("first");
String top = (String)stack.pop();
What happened?
• Thread A:
for( Iterator<String> itr = sl.iterator();
itr.hasNext(); ) {
System.out.println(itr.next());
}
• Thread B:
for( int i = 999999; i > 0; i-- ) {
sl.remove(i);
}
Thread A throws ConcurrentModificationException
immediately after thread B first modifies the List
2007 JavaOneSM Conference | Session TS-2890 | 35
Using java.util Collections
Concurrently
Additional safeguards needed for concurrent access
• Use client-side locking
• Subclass or wrap the collection:
public class WrappedList<T> implements List<T> {
private final List<T> list;
public WrappedList<T> list){ this.list = list; }
public synchronized void addIfAbsent(T x) {
if (!list.contains(x))
list.add(x);
}
}
// delegate other methods
}
For concurrent use, java.util collections must often
be locked for all operations, including iteration!
2007 JavaOneSM Conference | Session TS-2890 | 36
Concurrent Collections
No safeguards needed for java.util.concurrent classes
Collections in java.util.concurrent don’t
require external locking:
• Atomic operators provided where necessary
• ConcurrentMap operations
• atomic test-then-act: putIfAbsent, remove, replace
• Blocking{Queue|Deque} operations
• blocking operations: take, put
• operations from Queue or Deque now required to be atomic
• Iterators are snapshot or weakly consistent
• Never throw ConcurrentModificationException
Interface-based API:
Collection
SortedSet SortedMap
HashSet
ArrayList LinkedList HashMap WeakHashMap
SortedSet SortedMap
LinkedHashSet
LinkedHashMap
TreeMap
TreeSet
2007 JavaOneSM Conference | Session TS-2890 | 41
Collections in Java 5 and Java 6
Additions to the Collections Framework
• Top-level Interface
• Queue
• Subinterfaces
• Deque, NavigableMap, NavigableSet
• Concurrent interfaces in java.util.concurrent
• BlockingQueue, BlockingDeque,
ConcurrentMap, ConcurrentNavigableMap
• 18 implementation classes
Collection
ConcurrentNavigableMap
• Operations on NavigableSet
• ceiling/floor, higher/lower,
pollFirst/pollLast
• headSet,tailSet,subSet overloaded to allow choice of
inclusive or exclusive limits (unlike SortedSet operations)
TS-2890