The gobind framework is supposed to use reference counting to
keep track of objects (e.g. pointer to a Go struct, interface
values) crossing the language boundary. This change fixes two bugs:
1) no reference counting on Java object: Previously, the lifetime
of a Java object was manages in the following way.
a. The Java object is pinned in an internal map (javaObjs) when it's
constructed.
b. When Go receives the reference to the Java object, it creates a
proxy object and sets a finalizer on it. The finalizer signals Java
to unpin the Java object (remove from the javaObjs map).
c. The javaObjs map is also used to identify the Java object when
Go asks to invoke a method on it later.
When the same Java object is sent to Java more than once, and the
finalizer (b) runs after the first use, the second use of the Java
object can cause the crash described in golang/go#10933.
This change fixes the bug by reference counting the Java object.
Java side pins the Java object and increments the refcount whenever it
sees the object sent to Go (in Seq.writeRef). When the Go proxy
object's finalizer runs, the refcount is decremented. When the refcount
becomes 0, the object gets unpined.
2) race in Go object lifetime management: Pinning on a Go object
has been done when the Go object is sent to Java but the Go object
is not in the pinned object map yet. (bind/seq.WriteGoRef).
Unpinning the object occurs when Java finds there are no proxy objects
on its side. For this, Java maintains a reference count map (goObjs).
When the refcount becomes zero, Java notifies Go so the object is
unpinned. Here is a race case:
a. Java has a proxy object for a Go object.
b. Go is preparing for sending the same Go object. seq.WriteGoRef
notices the corresponding entry in the pinned object map already,
and returns. The remaining work for sending the object continues.
c. The proxy object in Java finalizes and triggers deletion of the
object from the pinned object map.
d. The remaining work for (b) completes and Java creates a new proxy
object. When a method is called for the Go object, the Go object is
already removed from the object map on Go side and maybe already GC'd.
This change fixes it by converting the pinned object map to reference
counter map maintained in Go. The counter increments for each
seq.WriteGoRef call. The finalizer of the proxy object in Java causes
a decrement of the counter.
Fixesgolang/go#10933.
Renables the skipped testJavaRefGC.
Change-Id: I0992e002b1050b6183689e5ab821e058adbb420f
Reviewed-on: https://go-review.googlesource.com/10638
Reviewed-by: David Crawshaw <crawshaw@golang.org>