JacobComLifetime.html 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. <H1>COM Object Lifetime in JACOB</H1>
  2. <H2>introduction</H2>
  3. JACOB Version 1.7 implements a new
  4. <a href="JacobThreading.html">Threading Model</a> that is more compatible with COM apartments. There is also an incompatibility between the Java object
  5. lifetime model and that of COM objects. COM Objects live and die by their reference count, whereas Java objects are collected
  6. by the Garbage Collector (GC) based on algortihms that are hidden from the user.
  7. <H2>COM Object Lifetime in JACOB Prior to Version 1.7</H2>
  8. In version 1.6 and earlier, JACOB objects which wrapped COM objects had
  9. <code>finalize()</code> methods that would call a native
  10. <code>release</code> method which would call a COM
  11. <code>Release</code>.
  12. <p></p>
  13. This has many problems. For one thing, the GC may take a long time to kick in and resource consumption may grow. However,
  14. the more problematic issue is that finalizers are called from a separate thread, and, as was discussed in the
  15. <a href="JacobThreading.html">Threading Model</a>
  16. document, this can result in COM errors if the object is running in an STA. Even if the object is running in an MTA, the
  17. finalizer may decide to run after we have terminated the thread that holds the component, in which case we would get fatal
  18. errors and crashes.
  19. <H2>COM Object Lifetime in JACOB in Version 1.7</H2>
  20. In Version 1.7, all JACOB objects which wrap COM objects extend
  21. <code>com.jacob.com.JacobObject</code>. This object has some special code to register itself with a
  22. <code>com.jacob.com.ROT</code> object which represents a Running Object Table (ROT). This table maps a Thread to the set of JacobObjects created in that
  23. thread. Therefore, when you call
  24. <code>ComThread.Release()</code>, the ROT checks whether that thread has created any objects, and these objects are released by calling their native
  25. <code>release</code> method (which is public).
  26. <p></p>
  27. This lifetime management method ties the lifecycle to the thread's lifecycle rather than the GC. The JacobObject's still
  28. have finalizers, but they will typically not perform the native
  29. <code>release</code> since that has already been called. The native
  30. <code>release</code> methods were written such that you can call them multiple times without worrying - since they zero out the native pointer
  31. when called the first time.
  32. <p></p>
  33. If you choose to call
  34. <code>release</code> methods on your objects yourself, that is allowed. In that case, when the thread is released the release calls will be no-ops.
  35. <p></p>
  36. It becomes important for you to call
  37. <code>ComThread.Release()</code> on any thread before you allow it to exit, otherwise you may get some random crashes later on in your code.