When you invoke a java stored procedure you will instantiate the internal JVM (Java Virtual Machine) to execute that code. Since 11gR1, you can clear your session state with functions in the DBMS_JAVA package.
DBMS_JAVA.endsession – this will clear your Java session state.
DBMS_JAVA.endsession_and_related_state – this will clear your Java session state. It will also clear other session-state related to running Java, such as output redirects.
As these are declared as functions, you must either select their values in a query use output in a pl/sql procedure call or assignment.
SQL> select dbms_java.endsession from dual; ENDSESSION --------------------------------------------------------------- java session ended SQL> select dbms_java.endsession_and_related_state from dual; ENDSESSION_AND_RELATED_STATE --------------------------------------------------------------- java session and permanent state ended
A third option is also supported – calling the java.lang.System.exit() method to terminate the JVM. In 10gR2 and prior versions, this was the only option.
To enable this functionality you first declare a pl/sql call specification for the Sytem.exit() method.
CREATE OR REPLACE PROCEDURE exit_jvm(arg NUMBER) AS LANGUAGE JAVA NAME 'java.lang.System.exit(int)' ; /
To use it, you can simply call it with a 0 to indicate a successful termination, or, if you want to simulate a failure, pass in a non-zero value. Calling System.exit() will raise an ORA-29515 exception, regardless of the exist code value.
SQL> CREATE OR REPLACE PROCEDURE exit_jvm(arg NUMBER) 2 AS 3 LANGUAGE JAVA 4 NAME 'java.lang.System.exit(int)' ; 5 / Procedure created. SQL> exec exit_jvm(0); BEGIN exit_jvm(0); END; * ERROR at line 1: ORA-29515: exit called from Java code with status 0 ORA-06512: at "SDS.EXIT_JVM", line 1 ORA-06512: at line 1 SQL> exec exit_jvm(-1); BEGIN exit_jvm(-1); END; * ERROR at line 1: ORA-29515: exit called from Java code with status -1 ORA-06512: at "SDS.EXIT_JVM", line 1 ORA-06512: at line 1
You can capture the exception and exit cleanly if you wish.
SQL> DECLARE 2 jvm_system_exit EXCEPTION; 3 PRAGMA EXCEPTION_INIT(jvm_system_exit, -29515); 4 BEGIN 5 exit_jvm(0); 6 EXCEPTION 7 WHEN jvm_system_exit 8 THEN 9 NULL; -- log the exit message if you want 10 END; 11 / PL/SQL procedure successfully completed.
Using this option mirrors the DBMS_JAVA.endsession functionality.
Hopefully these options will help. I wrote this article as a reference for myself after finding I had some old 9i-era code still using System.exit() that could be updated to the new (15+ years old at this point) DBMS_JAVA syntax.
And if, by chance, you happen to still be using an old pre-11g database, then hopefully wrapping a the java call specification will be helpful in your system too.
Thank you for reading. Questions and comments, as always, are welcome.