0

I am working on an Android project. My setup:

  • Host development machine: Macbook
  • Android studio Arctic Fox, 2020.3.1
  • Android Gradle Plugin Version 7.0.0
  • Gradle Version 7.0.2
  • JDK 11 located under Android Studio.app/Contents/jre/Contents/Home

When I try to import java.lang.ref.Cleaner in a java source file, I keep getting the "Cannot resolve symbol 'Cleaner'" compile error. Here is what the relevant parts of my build.gradle file looks like: enter image description here

After googling the issue for a while, the best explanation I could come up with is that Android is still on Java 8, but java.lang.ref.Cleaner is a Java 9+ feature. I tried selecting different versions of JDK in Android Studio, under the "Project Structure" menu, but it made no difference. Is it possible at all then to use Java 9 language features in an Android project?

DwayneDuane
  • 101
  • 3
  • 1
    Why do you need to use `Cleaner`? – dan1st Aug 11 '21 at 15:55
  • I am learning JNI and came across this article https://dhilst.github.io/2016/10/15/JNI-CPP.html. It is mentioned in the article that an object allocated in C++ is currently being leaked and the solution is left as an exercise to the reader. The solution I am thinking of involves creating a native method to deallocate the native object and invoking this method using a Cleaner. – DwayneDuane Aug 11 '21 at 16:28
  • 2
    Cleaners may not be executed and also have other problems. You might want to deallocate it manually after its last use. – dan1st Aug 12 '21 at 04:57
  • 2
    An dan1st said, the preferred way to deal with native resources is to deallocate them manually, or with `try(…)` where possible, and using GC based cleanup only as a last resort. Implementing a cleaner in an environment not offering it on its own like Android has been discussed in [this Q&A](https://stackoverflow.com/q/46144524/2711488) – Holger Aug 12 '21 at 08:44
  • @Holger, thank you for your reply. My background is in C++ and my first instinct was to go for something resembling RAII. But if the preferred method is to manually deallocate native resources, that is fine. Your suggestion of using try(...) means implementing the AutoCloseable interface, right? And just for curiosity's sake, what is the reason why Java 9+ features are unavailable to Android Studio despite it using JRE 11? – DwayneDuane Aug 12 '21 at 10:26
  • 1
    Right, the class encapsulating the resource must implement `AutoCloseable` or a subtype of it, to be usable with `try(…)`, which is the closest to RAII we have in Java. The JRE used by Android Studio has little relevance, what matters, is the availability of those class libraries on the target device which depends on the Android version. – Holger Aug 12 '21 at 13:30

0 Answers0