Is it necessary to call cleanup() before close() in a PythonInterpreter in Jython every time?
I've been reading the docs, but I don't find much information about this function. The javadocs don't say anything at all. The closest information I've found is here, in readthedocs, where they explain that a cleanup is necessary in some cases programming with threads, and I'm not even sure they refer to this particular function.
I wonder when I need to call cleanup()... and if the answer is always, then why would they make cleanup() and close() separate functions?
Okay, I've been reading the Jython source code and doing some tests. Here is what I found:
What
cleanup()does: It takes charge of the unhandeled resources, like running threads and files.What
cleanup()doesn't: Reset the state of the interpreter in any form; imported modules and defined variables are kept.The following examples show this behavior:
Example 1
Let's import a module, define a variable and open a file.
It outputs
The module
sysand the variablesaandfstill exist with the same values after the cleanup, but the open file is closed.Example 2
For this,
funcis a slow function that takes aprox 2 seconds to complete (more than a normalcleanup()).That outputs:
In the first execution, the main thread has plenty of time to check if
this alive and print it. In the second one, it always waits forthto finish, meaning that thecleanup()joins the thread somewhere.Conclusion
As @mzjn pointed out, the
close()function callscleanup()and that makes sense, so you never need to callcleanup()beforeclose(). The only case where you could need to call it manually would be if you wanted to continue using thePythonInterpreterbut needed to close all open files and join all threads.