Denis Murashko
Denis Murashko

Reputation: 129

How Is Serializable ThreadLocal?

I'm trying to serialize a neural network,but I'm faced with the fact that I don't know how to do it. My code.

public class Layer implements Serializable {
private final int size;
private ThreadLocal<Vec> out = new ThreadLocal<>();
private Activation activation;
private Optimizer optimizer;
private Matrix weights;
private Vec bias;
private double l2 = 0;

private Layer precedingLayer;

But when serializing, I get the following exception - Exception in thread "main" java.io.NotSerializableException: java.lang.ThreadLocal How can I serialize my class?

Upvotes: 1

Views: 685

Answers (1)

Hank
Hank

Reputation: 56

Because a field in your Layer class does not implement Serializable, java does not know how to serialize an instance of Layer.

Specifically, as the exception message indicates, ThreadLocal<Vec> out is one such field that cannot be serialized, and if look at the class you'll see that it does not implement the Serializable interface.

ThreadLocal: https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

Serializable: https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

You could probably make a class like this that will compile:

import java.io.Serializable;

public class SerializableThreadLocal<T> extends ThreadLocal<T> implements Serializable {

}

Then instantiate an instance of SerializableThreadLocal when you start off, like this:

private ThreadLocal<Vec> out = new SerializableThreadLocal<Vec>();

Upvotes: 1

Related Questions