开发者

find number of references to a java object or check whether it is referenced elsewhere

开发者 https://www.devze.com 2023-02-19 04:09 出处:网络
Scenario: I have code that mutates objects and other code that doesn\'t, i.e. it treats the objects it works with as immutable.

Scenario:

I have code that mutates objects and other code that doesn't, i.e. it treats the objects it works with as immutable. But in a setting with parallel working tasks this works reliably only if one can make sure that certain objects will not be modified from 3rd party or library code which could happen if there are references outside the scope of my code. One possibility is to always pass copies instead of the original objects. But sometimes one could save memory and time if one just knew that there are no other references to an object lingering around elsewhere.

Here is a pseudo coded generic "freeze" method that would take an object an开发者_如何学Pythond return an identical "immutable" one:

public <T> T freeze(T x) { 
    if immutable anyway then return x
    else if "not referenced in other objects" then return x
    else if x clonable then return clone of x
    else if x serializable then return serialized/deserialized x
    else ....
}

What I am looking for is the "not referenced in other objects" part.

Any suggestions?


You could keep track of a reference count for the object.

I don't believe there is anything in Java which do what you want. The GC could be used for something like this, but triggering a Full GC to perform this check is not a good idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消