并发链接队列:NotSerializableException

ConcurrentLinkedQueue: NotSerializableException

我需要序列化 ​​ConcurrentLinkedQueue。

public class Service implements Serializable { 
    private static Queue<Message> messages = new ConcurrentLinkedQueue<>(); 

    public class Serialize {
        public static Queue<Message> getMessages() 
        { 
            return messages; 
        } 
    }
}

正在尝试:

FileOutputStream fos = new FileOutputStream("filename");
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(Service.Serialize.getMessages());

结果:

java.io.NotSerializableException: server.Service at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548) at java.io.ObjectOutputStream.defaultWriteObject(ObjectOutputStream.java:441) at java.util.concurrent.ConcurrentSkipListMap.writeObject(ConcurrentSkipListMap.java:1430) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:988) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)

如何???

也许你应该摆脱内部 class 序列化并将方法放在服务中..

在这个 class 中的某个地方,您在 post 中省略了您正在使用并尝试序列化一个匿名内部 class,正如异常明确指出的那样。