[m-rev.] for review: add example of calling Mercury libraries from Java

Paul Bone paul at bone.id.au
Mon Dec 15 15:24:07 AEDT 2014


On Fri, Dec 05, 2014 at 10:49:27PM +1100, Paul Bone wrote:
> 
> In a workspace on my machine I've fixed the issue with creating the thread
> pool.  However there are some assumptions inside MercuryThreadPool that I
> made and will take longer to fix.  It looks as if the simplest fix will be
> to require users to call something to close the thread pool when they're
> finished with it.  So I can make the new MercuryRuntime class have a method
> called finalise() that does both run_finalisers() and stops the thread pool
> (if it's been started).  The more complicated solution is to make the thread
> pool threads "daemon" threads, which is Java-speak meaning that the threads
> will exit of the main thread exits.  The problem with that is that it may
> differ from other Mercury backends.  I beleive that we want all backends to
> wait for thread.spawn tasks to finish before finishing themselves, and
> depending on the application some of these tasks may need to write and close
> files.
> 
> I'm leaning towards the first solution, especially since there would be a
> run_finalisers() function anyway.  Does anyone see any problems with that?
> 

I have a change to add a MercuryRuntime class with a finalise() method.
However I've also found a mechanism in Java that allows me to run an
"atexit"-like task.  This needs me to modify the way the thread pool works
because "atexit" won't run unless the JVM is shutting down, and the JVM
won't shutdown while non-daemon threads are running (unless the user calls
exit()).  And the threads used by the thread pool are non-daemon threads.  I
can't make them daemon threads without either breaking the requirement that
the program waits for all threads to finish before exiting or adding extra
synchronisation.

It's easy enough to fix but it's a lower priority than some other work so
I'm happy to leave it for now.  If I implement it I will still keep the
finalise() method in case someone wants to explicitly run finalisers and
shutdown.

The only problem with requiring users to finalise the runtime explicitly is
if the main thread throws an exception and therefore skips the call to
finalise() then the JVM won't exit.  This can be worked-around by using
a finally block:

    public void main(String[] args) {
        try {
            // Run program
        }
        finally {
            MercuryRuntime.finalise();
        }

        System.exit(MercuryRuntime.getExitStatus());
    }

Thanks.



-- 
Paul Bone



More information about the reviews mailing list