EZ Jcom
Java to COM/ActiveX Bridge

Java Threads in EZ JCom

There are some issues involved in Java thread processing and COM thread processing, that EZ JCom users should be aware of.

EZ JCom simplifies the thread processing, so simple COM tasks require no attention to threading issues. However, for complex requirements, additional steps may be required.

By default

  • EZ JCom initializes COM in the STA (Single Threaded Apartment) model.
  • A single Windows message loop is created.
  • All COM requests are processed via the EZ JCom message loop.
This model will normally work with all COM objects, STA or MTA. But some situations require alteration to this model.

Method Invocation Serialization

One serious implication of the default EZ JCom threading model is that only one COM method can be called at a time. Let us say you have two threads, and the first one calls Method1 and the second one calls Method2. Then EZ JCom will serialize both calls. Suppose Method1 gets called first. Then as long as Method1 does not return, it will not be possible for the Method2 invocation to go ahead! Method2 will be placed in a wait state.

In some designs, this can be undesirable. There are two solutions:

  • Stop the Windows message loop by calling ezjcom.JComObject.JComStopWindowsMessageLoop() but retain STA. If your COM object does not support MTA, this is the only possible solution. But there are some caveats with this. First of all, theoretically COM requires the presence of a Windows loop. It is possible that some COM objects depend upon the presence of such a Windows loop. Secondly, if the windows message loop is stopped, all STA calls will be processed in their own threads. The Java program then has the responsibility to ensure that objects created in one thread are not used by another. Finally, this method cannot be used for COM objects that have a UI that you want to expose in Java.
  • Use MTA by setting the environment variable SET EZJCOM_MODE=MTA before running the program. But this requires that your COM object supports MTA.

Inefficient behavior with MTA objects

Some COM objects are designed for MTA model only. For such objects, using STA results in very inefficient behavior. If your methods are taking very long time to return, maybe switching to MTA is necessary. Check the documentation of your COM object to see if it requires MTA, and if necessary, set the environment variable, SET EZJCOM_MODE=MTA before starting the program.