Search code examples
javamultithreadingactivexwmijacob

JACOB library fails when used in multiple threads


I have a strange problem using JACOB from two consequently started identical threads. I have a utility class that uses a static ActiveXObject field for dispatching various requests to the WMI. The first thread works fine. When the second thread is started I get the following exception:

com.jacob.com.ComFailException: Can't map name to dispid: ExecQuery
at com.jacob.com.Dispatch.invokev(Native Method)
at com.jacob.com.Dispatch.invokev(Dispatch.java:858)
at com.jacob.com.Dispatch.callN(Dispatch.java:455)
at com.jacob.com.Dispatch.call(Dispatch.java:544)
at com.jacob.activeX.ActiveXComponent.invoke(ActiveXComponent.java:510)
at JacobWmiAdapter.getResultsList(JacobWmiAdapter.java:111)
at JacobWmiAdapter.getResultsList(JacobWmiAdapter.java:104)
at WindowsInfoCollector.getConnectionInfo(WindowsInfoCollector.java:516)
at WindowsInfoCollector.collect(WindowsInfoCollector.java:118)
at DiagnosisExecutor.execute(DiagnosisExecutor.java:128)
at DiagnosisExecutor.run(DiagnosisExecutor.java:160)
at java.lang.Thread.run(Thread.java:662)

The thread is started by a mouse click from a GUI, but the error is reproducible manually:

        DiagnosisExecutor dex = new DiagnosisExecutor();
        Thread thread1 = new Thread(dex);
        Thread thread2 = new Thread(dex);

        thread1.start();
        thread1.join();
        Thread.sleep(1000);
        thread2.start();

It seems to me that some allocated resources are not being released correctly when the thread that uses them terminates. Any hints?

Update: JACOB Version 1.14.3


Solution

  • I haven't used the latest version of JACOB with it's new threading model, but older versions were definitely not thread safe. As of version 1.7 > they have improved the threading model to better reflect the underlying COM components, but you have to determine whether said component is MTA or STA, and then initialize JACOB classes appropriately. Refer to the JACOB documentation for how to properly adapt your application according to its requirements.