首页 > 解决方案 > OpenHFT Chronicle Queue 写入字段标记为瞬态

问题描述

好的,所以我有几个基本上看起来像这样的类。

public class Foo implements Serializable {
    private A a;

    //More code
}

public class A implements Serializable {
    public Vector vector = new Vector();

    //More code
}

public class B implements Serializable {
    private transient A parent;

    //More code
}

public static void main(String[] args) {

    A a = new A();
    a.vector.add(new B(a));

    Foo foo = new Foo(a);
    //More code to write foo with OpenHFT
}

所以这里的奇怪之处在于 A 和 B 周期性地指向对方,其中Ahas Bin its attributevectorBhas Aas its attribute parent。通常,如果您尝试编写它,这将是一个问题,因为它会导致无限循环。因此使用transient关键字 on parent

但是,出于某种原因,OpenHFT 没有注册设置为瞬态的事实parent并且仍在尝试编写它,导致我得到一个 StackOverflowException(呵呵,实际上是在 Stack Overflow 上询问 StackOverflowException,这是第一次)。

关于为什么会发生这种情况的任何建议?

顺便说一句,我正在使用 Maven 导入 OpenHFT,并且我使用的是 5.17.17 版本

标签: javachronicle

解决方案


我不知道您是如何获得 StackOverflowException 的,您的代码(进行了一些明显的修改以使其有意义)对我有用:

public class Test {
    public static class Foo implements Serializable {
        private A a;

        public Foo(A a) {
            this.a = a;
        }

        //More code
    }

    public static class A implements Serializable {
        public Collection<B> vector = new Vector<>();

        //More code
    }

    public static class B implements Serializable {
        private transient A parent;
        private String name;

        public B(A a, String name) {
            this.parent = a;
            this.name = name;
        }

        //More code
    }

    public static void main(String[] args) {

        A a = new A();
        a.vector.add(new B(a, "name"));

        Foo foo = new Foo(a);

        Bytes bytes = Wires.acquireBytes();
        final ValueOut out = WireType.JSON.apply(bytes).getValueOut();
        out.marshallable(foo);

        System.err.println(bytes.toString());
    }
}

这将输出:

"a":{"vector":[ {"name":"name"} ]
}

因此很明显瞬态字段被忽略了。


推荐阅读