SQL/MX Programming Manual for Java
SQLJ Programming
HP NonStop SQL/MX Programming Manual for Java—523726-003
3-25
Coding a Multithreaded SQLJ Program
Using Different Connection Contexts for Each Thread
Each connection context object has its own default execution context. If you do not
specify explicit execution contexts in an SQLJ program, the program uses the same
default execution context for all statements that use the same connection context
object. If you explicitly specify different connection contexts for each thread, the
threads will use different execution contexts by default.
This example uses different connection contexts for each thread:
public class MultiThread2 extends Thread {
...
//main() method
public static void main (String [] args) {
try {
#sql { MODULE samdbcat.sales.mt2mod };
showPrices();
//Instantiating Thread objects
MultiThread2 t1 = new MultiThread2(new BigDecimal(186),
(double)15);
MultiThread2 t2 = new MultiThread2(new BigDecimal(186),
(double)2);
//Starting the execution of the threads
t1.start();
t2.start();
t1.join();
t2.join();
showPrices();
}
...
//Overriding the run() method
public void run() {
try {
Class.forName("com.tandem.sqlmx.SQLMXDriver");
Connection conn =
DriverManager.getConnection("jdbc:sqlmx:");
//Instantiating an explicit connection context object
SQLMXCtx ctx = new SQLMXCtx(conn);
...
#sql [ctx] { UPDATE samdbcat.sales.parts
SET price = price * (1 + (:percent/100))
Caution. The static variable associated with the default connection context is shared among
threads that use the default connection context. If explicit connection contexts use the default
connection context, invoking the close() method affects every thread that uses the default
connection. If one thread closes the default connection context before another thread runs, the
JDBC connection disappears. When a second thread tries to use the closed connection, an
exception occurs.