0

This is the scenario:

I have instantiated a String in a class, then I have obtained its position in HEAP:

public class UnsafeExperiment {

    static String s = "ciao";

    public UnsafeExperiment() throws Exception {
        Unsafe unsafe = getUnsafeInstance();
        Field field = this.getClass().getDeclaredField("s");
        field.setAccessible(true);

        long position = unsafe.staticFieldOffset(field);
        wait();

    }

    private  Unsafe getUnsafeInstance() throws Exception {
        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        return (Unsafe) theUnsafeInstance.get(Unsafe.class);
    }
}

From another class, how can I call the String in the HEAP using its address ? (please, I am not interested in consideration about opportunity to use this approach.. I know from the library involved it is unsafe )

Andrea T
  • 3,035
  • 4
  • 23
  • 39
  • Why not just pass a reference to the string? Why do you need to worry about its location in the heap? – Andy Turner Nov 24 '15 at 15:45
  • 2
    Why do you want to do this? The point of managed languages, such as Java, is to not worry about such things – Vince Nov 24 '15 at 15:46
  • It is an use case in a quite complex scenario for a framework for Reactive Microservices Systems:. Long thing made short: I have a DeferredResult from a REST interface and I need to set its Result in another application: unfortunately I can't pass the DeferredResult as Reference, but as Serialized Object: so if I modify it in the other Application the original DeferredResult won't be modified. For that motive I need to send back from the second application the original address in HEAP to an observer on the first application where the DeferredResult is: when I have it I can set the result. – Andrea T Nov 24 '15 at 16:00
  • So these two applications must share a reference to an object? Have you looked into RMI? You could remotely invoke a method which sets/obtains any values that are shared between the applications. One could hold the reference, the other could mutate/access values from it – Vince Nov 24 '15 at 16:07
  • As for replacing data in the heap, I highly recommend against any attempts at it. GCed languages compact the heap after GCs, which results in objects being moved around. For all you know, you could reference part of the heap, a GC could occur resulting in compacting, leaving your heap reference useless (or referencing the wrong data) – Vince Nov 24 '15 at 16:10
  • The scope of this trick is to make a Reactive / Event driven pattern in the framework. At least to verify whether it is possible to use such solution... – Andrea T Nov 24 '15 at 16:10

1 Answers1

0

You can access the string from its position as follows:

String s = (String) unsafe.getObject(UnsafeExperiment.class, position);
dejvuth
  • 6,986
  • 3
  • 33
  • 36