Java のネイティブ シリアライゼーションを使用すると、断続的に ClassCastExceptions が発生します。
java.lang.ClassCastException: myCompany.MyClass$MembershipServiceMethod cannot be cast to java.io.ObjectStreamClass
または(あまり頻繁ではありません)
java.lang.ClassCastException: java.lang.String cannot be cast to java.io.ObjectStreamClass
特定の不変クラスのオブジェクトを逆シリアル化するとき。つまり、例外は特定のシリアル化された表現に対して常にスローされますが、ほとんどのオブジェクトは正常にシリアル化および逆シリアル化できます。
public final class ServiceInteractionImpl implements ServiceInteraction, Serializable {
private static final long serialVersionUID = 1L;
private final InteractionSource source;
private final long startTime;
private final InteractionType type;
private final ServiceMethod method;
private final long duration;
private final String accompanyingMessage;
public ServiceInteractionImpl(final ServiceMethod method,
final InteractionSource source,
final InteractionType type,
final long startTime,
final long duration,
final String accompanyingMessage) {
this.source = source;
this.startTime = startTime;
this.duration = duration;
this.type = type;
this.method = method;
this.accompanyingMessage = accompanyingMessage;
}
...
getters and canonical methods
}
ここで、InteractionSource、InteractionType、および ServiceMethod は列挙型です。何百万ものオブジェクトをシリアライズおよびデシリアライズする Junit テストを実行しているローカル環境では、これを再現できません。
書き込みコードはこちら
fileLock.lock();
try {
final File recordFile = new File(recordFileName);
boolean appendToFile = false;
if (recordFile.exists()) {
appendToFile = true;
}
final OutputStream fileOutputStream = new FileOutputStream(recordFileName, true);
final OutputStream buffer = new BufferedOutputStream(fileOutputStream);
ObjectOutput output;
if (appendToFile) {
output = new AppendableObjectOutputStream(buffer);
} else {
output = new ObjectOutputStream(buffer);
}
int localSerializedInteractionsCount = 0;
try {
for (final ServiceInteraction interaction : tempCollection) {
output.writeObject(interaction);
output.flush();
localSerializedInteractionsCount++;
rollBackCollection.remove(interaction);
}
} finally {
output.close();
serializedInteractionCount += localSerializedInteractionsCount;
}
} catch (IOException e) {
LOGGER.error("could not write to file", e);
//some roll-back code
} finally {
fileLock.unlock();
}
AppendableObjectOutputStream については、ObjectOutputStreamへの追加を参照してください。
どんな助けでも大歓迎です。