Object Reference Cycle

Apr 2, 2018
Object Reference Cycle
  • In this page, we will talk about what is an object reference cycle, and how to prevent it. (It cannot be fixed.)

    Let's take a look at the example below:
    Code (Java):
    package me.rcextract;

    import com.rcextract.minecord.sql.DatabaseSerializable;

    public class A {
        private B b;
        ...
        @Override
        public ArrayMap<String, Object> serialize() {
            ArrayMap<String, Object> map = new ArrayMap<String, Object>();
            map.put("b", b);
            return map;
        }

    }
    Code (Java):
    package me.rcextract;

    import com.rcextract.minecord.sql.DatabaseSerializable;

    public class B {
        private A a;
        ...
        @Override
        public ArrayMap<String, Object> serialize() {
            ArrayMap<String, Object> map = new ArrayMap<String, Object>();
            map.put("a", a);
            return map;
        }

    }
    When serializing A, the SQLObjectConverter will try to save the B referenced first, so it can achieve the location (table name and row id) where it is saved, and make a String reference. However, this also happens when saving B, so a loop will be created, and as a result, StackOverflowError will occur.

    The only solution is to remove one of the references.
  • Loading...
  • Loading...