并行化Java快速序列化

时间:2018-09-29 14:22:21

标签: java serialization parallel-processing fst

这是我第一次使用Java中的线程。 我正在尝试并行化快速序列化。 但是我遇到以下错误:

Exception in thread "pool-1-thread-1" java.lang.RuntimeException: Class org.nustaq.serialization.FSTObjectOutput does not implement Serializable or externalizable

那么如何正确并行化快速序列化? 我的错误在哪里?

这是我可运行的课程:

public class RunnableTestClass implements Serializable, Runnable {

FSTObjectOutput out;
ObjectOutputStream stream;
private long a,b,c,d,e,f,g,h;
public RunnableTestClass(long i, ThreadLocal<FSTConfiguration> conf) throws Exception {
    a = i;
    //some more
    stream = new ObjectOutputStream(new FileOutputStream("out/FST.ser_parallel"));
    out = conf.get().getObjectOutput(stream);
}

@Override
public void run() {
    try {
        out.writeObject(this, TestClass.class);
        out.flush();
        stream.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

这是我的主音:

public class Test {

public static FSTConfiguration[] configurations = new FSTConfiguration[4];
public static ThreadLocal<FSTConfiguration> conf = new ThreadLocal<FSTConfiguration>() {
    @Override
    protected FSTConfiguration initialValue() {
        return configurations[((int) (Thread.currentThread().getId() % configurations.length))];
    }
};
static {
    for (int i = 0; i < configurations.length; i++) {
        configurations[i] = FSTConfiguration.createDefaultConfiguration();
    }
}

public static void main(String [ ] args) {

    conf.get().registerClass(TestClass.class);
    conf.get().setShareReferences(false);

    ExecutorService executor = Executors.newFixedThreadPool(4);

    try {
        for (int i = 0; i < 10; i++) {
            Runnable worker = new RunnableTestClass(i, conf);
            executor.execute(worker);
        }
        executor.shutdown();
    } catch (Exception e) {
        System.out.println(e);
    }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

错误是,我正在尝试在Runnable类中序列化ObjectOutput。 我以这种方式解决了这个问题:

public class RunnableTestClass implements Serializable, Runnable {

private FSTObjectOutput out;
private ObjectOutputStream stream;
private TestClass object;

public RunnableTestClass(long i, ThreadLocal<FSTConfiguration> conf) throws Exception {
    object = new TestClass(i);
    stream = new ObjectOutputStream(new FileOutputStream("out/FST.ser_parallel"));
    out = conf.get().getObjectOutput(stream);
}

@Override
public void run() {
    try {
        out.writeObject(object, TestClass.class);
        out.flush();
        stream.close();
    } catch (IOException e) {
        System.out.println(e);
    }
}

}

所以我只序列化“对象”对象。