When will Java go mainstream like Python?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 26 01:58:07 CET 2010

On Thu, 25 Feb 2010 17:11:32 -0700, Chris Gray wrote:

> I'm by no means an expert, but how does reference counting deal with
> arbitrary long cycles of references (btw I've *written* a simple
> reference counter for a programming language)?

It doesn't, or at least the CPython one doesn't.

In CPython, even a short reference cycle defeats it, which is why CPython 
also uses a second garbage collector. If we turn that off, we can see how 
even a one-element cycle defeats reference counting:

>>> import gc
>>> gc.disable()
>>> class K:
...     def __del__(self):
...             print "Bye now"
>>> k = K()
>>> del k  # Test it works as expected.
Bye now
>>> k = K()  # Now try with a cycle.
>>> k.attr = k
>>> del k

Normally, you would clear the ref cycle this way:

>>> gc.collect()

But in this case it doesn't work because the object in the cycle has a 
__del__ method, and Python can't predict a safe order to run the __del__ 
method. (I'm surprised that this is an issue with a single object, but 
what do I know?) So we have to inspect the list of garbage, manually 
break the cycle, clear new references we've created, and then it will be 
garbage collected:

>>> gc.garbage[0].attr = None  # Break the cycle
>>> del gc.garbage[:]
Bye now

This is one reason why __del__ methods are not recommended.

> When I asked someone whose knowlege of Java I trust, he said that modern
> Java's do both reference counting and garbage collection. That was 2 or
> 3 years ago. I would have guessed that Python was the same.

CPython has both now. Jython uses whatever the Java implementation uses, 
and IronPython uses .Net's memory management scheme. Other Pythons do 
whatever they like :)

Some interesting information here:



More information about the Python-list mailing list