Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have a concept of reference ownership or noncopyable classes?

Tags:

java

I would like to have some guarantee that instances of some particular class Content is only accessed by its "owner", and if another object wants the same Content it needs to take a deep copy. Coming from C++ I would achieve that using a unique_ptr, is there anything similar in Java?

Currently I am resolving this by just keeping the Content private everywhere I keep one and paying attention to creating a new Content (the constructor implements the deep copy mechanism) on a getContent. But I have no means of enforcing possible other users of the Content class to follow the same pattern, it's easy to forget. It would be nicer if it could take care of itself somehow, like not being copyable.

I realize that it goes somewhat against the spirit of the language, but in some cases I think it's justified. For example, if Content represents some stream of data that is modified even by reading it. I thought, if not in the core language, maybe there is some @interface for compile-time checking or a way of creating one?

Edit: The idea is that the owner can modify the object freely, before or after taking copies, and if someone takes a deep copy, they can modify theirs (not affecting the original), so making the Content immutable is a bit too harsh (unless I'm misunderstanding what that implies).

like image 463
The Vee Avatar asked Mar 11 '23 18:03

The Vee


2 Answers

There are a couple of common strategies here:

Privacy with defensive copying

In this strategy, you'd have the owner have a private reference to the content, and if it's appropriate for it to give out copies of that content, to do so via a defensive copy:

class Owner {
    private Content content;

    // ...unnecessary detail omitted...

    public Content getContent() {
        return new Content(this.content);
    }
}

The Cloneable interface can sometimes be useful here.

Immutable objects

The other common strategy is to use immutable objects (e.g., ensure that Content, once instantiated, cannot be modified). Then you don't care who has a reference to the content, since they cannot change it.

like image 75
T.J. Crowder Avatar answered Mar 13 '23 06:03

T.J. Crowder


No there isn't.

Once you have established a reference to an object, there's absolutely nothing you can do to stop someone form assigning another reference to that object via that established reference.

Java programmers get round this by making objects immutable (see java.lang.String). Then you ought not give two hoots about who else is referring to a particular instance.

like image 34
Bathsheba Avatar answered Mar 13 '23 07:03

Bathsheba