10.43.6.1 Lifetime of SPTerms and Prolog Memory

There are three separate memory areas involved when manipulating Prolog terms from Java using SPTerm objects. These areas have largely independent life times.

  1. The SPTerm object itself.
  2. Creating SPTerm object also tells Prolog to allocate an SP_term_ref. SP_term_refs have a life-time that is independent of the lifetime of the corresponding SPTerm object.
  3. Any Prolog terms allocated on the Prolog heap. An SPTerm refer to a Prolog term indirectly via a SP_term_ref.

A SP_term_ref ref (created as a side-effect of creating a SPTerm object) will be reclaimed if either:

An SPTerm object will be invalidated (and eventually reclaimed by the garbage collector) if the corresponding SP_term_ref is reclaimed as above. If passed an invalidated SP_term_ref, most methods will throw an IllegalTermException exception.

A Prolog term (allocated on the Prolog heap) will be deallocated when:

Please note: it is possible to get a SPTerm object and its SP_term_ref to refer to deallocated Prolog terms, in effect creating “dangling” pointers in cases where the SPTerm would ordinarily still be valid. This will be detected and invalidate the SPTerm:
     {
       SPTerm old = new SPTerm(sp);
       SPQuery q;
     
       q = sp.openQuery(....);
       ...
       old.consFunctor(...);  // allocate a Prolog term newer than q
       ...
       q.nextSolution(); // or q.close()
       // error:
       // The SP_term_ref in q refers to an invalid part of the Prolog heap
       // the SPTerm old will be invalidated by q.nextSolution()
     }

Send feedback on this subject.