View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.serialization;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufOutputStream;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.handler.codec.MessageToByteEncoder;
22  import io.netty.util.Attribute;
23  import io.netty.util.AttributeKey;
24  
25  import java.io.ObjectInputStream;
26  import java.io.ObjectOutputStream;
27  import java.io.OutputStream;
28  import java.io.Serializable;
29  
30  /**
31   * An encoder which serializes a Java object into a {@link ByteBuf}
32   * (interoperability version).
33   * <p>
34   * This encoder is interoperable with the standard Java object streams such as
35   * {@link ObjectInputStream} and {@link ObjectOutputStream}.
36   */
37  public class CompatibleObjectEncoder extends MessageToByteEncoder<Serializable> {
38  
39      private static final AttributeKey<ObjectOutputStream> OOS =
40              AttributeKey.valueOf(CompatibleObjectEncoder.class, "OOS");
41  
42      private final int resetInterval;
43      private int writtenObjects;
44  
45      /**
46       * Creates a new instance with the reset interval of {@code 16}.
47       */
48      public CompatibleObjectEncoder() {
49          this(16); // Reset at every sixteen writes
50      }
51  
52      /**
53       * Creates a new instance.
54       *
55       * @param resetInterval
56       *        the number of objects between {@link ObjectOutputStream#reset()}.
57       *        {@code 0} will disable resetting the stream, but the remote
58       *        peer will be at the risk of getting {@link OutOfMemoryError} in
59       *        the long term.
60       */
61      public CompatibleObjectEncoder(int resetInterval) {
62          if (resetInterval < 0) {
63              throw new IllegalArgumentException(
64                      "resetInterval: " + resetInterval);
65          }
66          this.resetInterval = resetInterval;
67      }
68  
69      /**
70       * Creates a new {@link ObjectOutputStream} which wraps the specified
71       * {@link OutputStream}.  Override this method to use a subclass of the
72       * {@link ObjectOutputStream}.
73       */
74      protected ObjectOutputStream newObjectOutputStream(OutputStream out) throws Exception {
75          return new ObjectOutputStream(out);
76      }
77  
78      @Override
79      protected void encode(ChannelHandlerContext ctx, Serializable msg, ByteBuf out) throws Exception {
80          Attribute<ObjectOutputStream> oosAttr = ctx.attr(OOS);
81          ObjectOutputStream oos = oosAttr.get();
82          if (oos == null) {
83              oos = newObjectOutputStream(new ByteBufOutputStream(out));
84              ObjectOutputStream newOos = oosAttr.setIfAbsent(oos);
85              if (newOos != null) {
86                  oos = newOos;
87              }
88          }
89  
90          synchronized (oos) {
91              if (resetInterval != 0) {
92                  // Resetting will prevent OOM on the receiving side.
93                  writtenObjects ++;
94                  if (writtenObjects % resetInterval == 0) {
95                      oos.reset();
96                  }
97              }
98  
99              oos.writeObject(msg);
100             oos.flush();
101         }
102     }
103 }