Threads and tasks example

If your CICS® Java™ application is running within an OSGi or Liberty environment, you can run work under a separate thread on a separate CICS task/transaction by using the CICSExecutorService.

Submit a Java Runnable or Callable object to the Executor service and the submitted application code will run on a separate thread under a new CICS task. Unlike normal threads created from Java, Executor controlled threads have access to the JCICS API and CICS services. In a CICS OSGi or Liberty environment you can use standard OSGi APIs to find the CICSExecutorService, or you can use the JCICS API convenience method CICSExecutorService.runAsCICS(), which finds the service and submits the Runnable or Callable object on your behalf.

Note: For non-HTTP requests in Liberty, a CICS task is created only when the first JCICS or JDBC DataSource with type 2 connectivity call is made.
The following example shows an excerpt of a Java class that submits a Runnable piece of application code to the CICSExecutorService. The application code simply writes to a CICS TSQ.
public class ExecutorTest
{
    public static void main(String[] args)
    {
        // Inline the new Runnable class
        class CICSJob implements CICSTransactionRunnable
        {
            public void run()
            {
                // Create a temporary storage queue
                TSQ test_tsq = new TSQ();
                test_tsq.setType(TSQType.MAIN);

                // Set the TSQ name
                test_tsq.setName("TSQWRITE");

                // Write to the temporary storage queue
                // Use the CICS region local CCSID so it is readable
                String test_string = "Hello from a non CICS Thread - "+ threadId;
                
                try
                {
                    test_tsq.writeItem(test_string.getBytes(System.getProperty("com.ibm.cics.jvmserver.local.ccsid")));
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public String getTranid()
            {
                // *** This transaction id should be installed and available ***
                return "IJSA";
            }
        }

        // Create and run the new CICSJob Runnable
        Runnable task = new CICSJob();
        CICSExecutorService.runAsCICS(task);
    }
}