Skip to content

Interrupt user threads when Python is exiting

This addresses the case where non-daemon threads are out of control, yet we still want to be able to cleanly exit.

An example which this addresses:

import time
import jpype as jp

import cmmnbuild_dep_manager

def in_background():
    while True:
        print('In background')
        time.sleep(10)

def block_call():
    Thread = jp.JClass("java.lang.Thread")
    t = Thread(in_background)
    t.setDaemon(False)
    t.start()

    while True:
        try:
            print('foo')
            time.sleep(4)
        except Exception:
            return

def main():
    jp.startJVM()

    mgr = cmmnbuild_dep_manager.Manager()
    mgr.start_jpype_jvm()

    Thread = jp.JClass("java.lang.Thread")

    tr = Thread(block_call)
    tr.setDaemon(True)
    tr.start()
    time.sleep(1)

if __name__ == '__main__':
    main()

@mihostet - I'd really appreciate your thoughts on this. There is a known issue with JAPC/CMW which means that an ActiveMQ user thread is blocking exit from Python. If this _interrupt_java_user_threads gets called it is because Python is exiting: this fact alone makes me more comfortable with calling interrupt on those user Java threads, but it is still a bit of a workaround that I don't love. Thoughts very welcome.

Edited by Philip Elson

Merge request reports