1   /*
   2    * Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
   3    * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
   4    */
   5 
   6   package java.io;
   7 
   8   /**
   9    * Context during upcalls from object stream to class-defined
  10    * readObject/writeObject methods.
  11    * Holds object currently being deserialized and descriptor for current class.
  12    *
  13    * This context keeps track of the thread it was constructed on, and allows
  14    * only a single call of defaultReadObject, readFields, defaultWriteObject
  15    * or writeFields which must be invoked on the same thread before the class's
  16    * readObject/writeObject method has returned.
  17    * If not set to the current thread, the getObj method throws NotActiveException.
  18    */
  19   final class SerialCallbackContext {
  20       private final Object obj;
  21       private final ObjectStreamClass desc;
  22       /**
  23        * Thread this context is in use by.
  24        * As this only works in one thread, we do not need to worry about thread-safety.
  25        */
  26       private Thread thread;
  27 
  28       public SerialCallbackContext(Object obj, ObjectStreamClass desc) {
  29           this.obj = obj;
  30           this.desc = desc;
  31           this.thread = Thread.currentThread();
  32       }
  33 
  34       public Object getObj() throws NotActiveException {
  35           checkAndSetUsed();
  36           return obj;
  37       }
  38 
  39       public ObjectStreamClass getDesc() {
  40           return desc;
  41       }
  42 
  43       private void checkAndSetUsed() throws NotActiveException {
  44           if (thread != Thread.currentThread()) {
  45                throw new NotActiveException(
  46                 "not in readObject invocation or fields already read");
  47           }
  48           thread = null;
  49       }
  50 
  51       public void setUsed() {
  52           thread = null;
  53       }
  54   }