Scala have wealth of immutable structure.
I wondered how do Scala manage excessive allocation and deallocation of such objects. How does it look for existing sublists when, e.g. concatenating 1 to List(1,2,3). How does it track a certain List is not used, and allow the garbage collector to release it?
I would design it roughly like this
class List {
private Map<Integer,WeakRef<List>> listCache;
public List(Integer head,List tail) {...}
public synchronized List prepend(Integer i) {
if (listCache.get(i) != null) {
if (listCache.get(i).get() == null) {
listCache.put(i,new List(i,this));
}
}
}
How does Scala design that? Does it handle excessive allocations and deallocations well? What does it do about threading?
Scala doesn’t manage the deallocation of these objects at all. They are created on the heap as normal JVM objects, and garbage collected by the JVM just like any other Java or Scala object. As the comments on your question point out, it doesn’t re-use lists created from previous calls to List() – it is always a new object.
To clarify the situation with concatenating lists – in this case, the resulting List object does hold a reference to the two ends of the list, but it still isn’t doing any special caching of previously used lists or anything like that.