Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there "smart pointers" in Java?

Are there anything along the lines of C++ smart pointers in Java?

like image 206
garima Avatar asked Jan 24 '11 15:01

garima


4 Answers

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.

like image 98
Aleksandr Dubinsky Avatar answered Oct 07 '22 02:10

Aleksandr Dubinsky


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.'

like image 23
jjnguy Avatar answered Oct 31 '22 21:10

jjnguy


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.

like image 7
sfussenegger Avatar answered Oct 31 '22 21:10

sfussenegger


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.

like image 6
Neil Avatar answered Oct 31 '22 21:10

Neil