Are there anything along the lines of C++ smart pointers in Java?
If you are looking for deterministic destruction or reference counting, which gives you timely control over object lifetime for the purpose of efficiently using resources (something which garbage collection does not give you), then Java offers two things.
1) The most common solution (used all over Java) is the Closeable
/AutoCloseable
pattern. It is a simple pattern. Each object that needs deterministic destruction has an owner, and the owner is responsible for calling close
. (The object may have multiple users, but a single owner.) This is used for file handles, network sockets, etc.
2) A much rarer option is reference counting, where an object can have multiple owners (and typically, there is no clear distinction between users and owners). This is what C++ shared_ptr
achieves. Look at almson-refcount, which is a library I wrote that implements reference counting.
To clarify, deterministic destruction is necessary in Java when dealing with any kind of resource that is not memory. The garbage collector effectively manages memory with its lazy approach. However, you cannot rely on the garbage collector to manage any other resources. This is why finalize
has been deprecated in Java 9.
All of Java's 'pointers' (references) are Smart Pointers.
Java is run in a managed environment. Which means that Java uses a garbage collector to clean up variables that are no longer referenced any more.
Java's references are slightly different from pointers though. Java abstracts away all of the pointer values and math that you see in C++. So, anytime you create a new object and store it to a variable, you are storing it into Java's version of a 'smart pointer.'
I've only heard of smart pointers in the context of memory management. As memory management is at the core of the Java platform, there's obviously no need for that.
The closest matches that come to mind are java.lang.ref.WeakReference and java.lang.ref.SoftReference as they allow to customize garbage collection to some degree.
Yes and no. No in that, nothing like a pointer object exists in Java. Yes in the sense that every object is a "smart pointer", meaning it's subjected to garbage collecting and takes care of its own lifetime so to speak.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With