https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
p

Philip Dukhov

12/03/2020, 2:12 AM
Kotlin objects seems not releasing when created in swift code. I have a sample kotlin class `class Test {}`:
Copy code
var test: Test?
weak var testW: Test?

func f() {
	testW = Test()
	print(testW) // non nil, unlike Swift class instance. 
	DispatchQueue.main.async { [weak self] in
	    print(self?.testW) // now nil, kind of ok
	}
}

func f() {
	test = Test()
	testW = test
	DispatchQueue.main.async { [weak self] in
	    self?.test = nil
	}
	DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
	    print(self?.testW) // not nil, seems it's not gonna be released, we have a leak
	}
}
Why in the second case it not get’s release at all? It shouldn’t be captured by the block.. How can I release a kotlin object?
a

Artyom Degtyarev [JB]

12/03/2020, 8:14 AM
Hello, @Philip Dukhov! The behaviour you observe here is about Kotlin/Native memory management guarantees - while the
test
was marked as released, the collector did not grab it yet. But it will do it at the end of execution or after some amount of time. To verify this one can either do some other operations, and check
testW
after that, or call GC manually using
kotlin.native.internal.GC.collect()
method(please write a wrapper to call it from Swift, it is not exposed to the framework’s API by default). For more info, please check this and this discussion at the K/N Github.
p

Philip Dukhov

12/03/2020, 9:07 AM
I tried asyncAfter 5 secs and the object is still there🤔 Will check out the links, thanks
a

Artyom Degtyarev [JB]

12/03/2020, 9:12 AM
Five seconds waiting won’t work, IIRC GC.collect() is being called automatically on new allocations or after some relatively long time. Wrap it and try calling it directly from swift, this should be the easiest way to check that the collector works.
👍 1
p

Philip Dukhov

12/03/2020, 9:20 AM
ok now I got it how it works, thanks for the explanations!