Rekha
Rekha

Reputation: 1433

What happens if i don't mark a non-serializable field as transient in java?

public class PersistentAnimation implements Serializable, Runnable
         {
         private Thread animator;
         private int animationSpeed;
         public PersistentAnimation(int animationSpeed)
        {
         this.animationSpeed = animationSpeed;
        animator = new Thread(this);
           }
               public void run()
          {
             while(true)
            {
               // do animation here
         }

Here animator is not marked as transient? Will it still be persisted?

Upvotes: 2

Views: 222

Answers (2)

Wyzard
Wyzard

Reputation: 34571

Java will try to serialize it, see that it's not Serializable, and throw a NotSerializableException.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 692121

No, because Thread does not implement the Serializable interface. You'll have an exception when trying to serialize an instance of this class.

Straight from the javadoc of Serializable:

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Upvotes: 5

Related Questions