jSegue contains support code to help you create and use COM Apartment Model Threads. COM interfaces that are marked for Apartment Model Threading should only be called from the thread they are created on. Futhermore, the Apartment Model Thread must pump Windows messages.
Use tlb2java
with the -check_apartment
option to generate
Java bindings to a COM component that is marked as using Apartment
Model Threading. tlb2java
will automatically generate
checks that will throw an exception if you call a method on an
interface created on a different thread. Additionally, the
IUnknown.finalize
method will use the Apartment Model
Thread to call Release
.
Use OleThread
to create a thread that is a COM
Apartment Model Thread. OleThread
creates a new
thread and sets up the necessary Windows message pump.
OleThread t = new OleThread("A Apartment Thread"); t.startAndInit();Once the thread is started you can execute code on that thread by using
ole_thread.invokeLater
or
ole_thread.invokeAndWait
. These are similar to
java.awt.EventQueue.invokeLater
and
java.awt.EventQueue.invokeAndWait
.
try { t.invokeAndWait(new Runnable() { public void run() { // this block of code runs on the "A Apartment Thread" // ... } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); }