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 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)
    {
    	// Get the parent task
    	final Task parentTask = Task.getTask();
    	
        // Inline the new Runnable class
        class CICSJob implements CICSTransactionRunnable
        {
            public void run()
            {
            	// Get the child task
            	Task childTask = Task.getTask();
            			
                // Create a temporary storage queue
                TSQ testTsq = new TSQ();
                testTsq.setType(TSQType.MAIN);

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

                // Write to the temporary storage queue
                String message = "Hello from a transaction: "+ childTask.getTransactionName() + ", " +
                		"started as a Java thread from transaction: " + parentTask.getTransactionName();
                try
                {
                	testTsq.writeString(message);
                }
                catch (CicsException 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);
    }
}