1 /*
2 * Copyright 2013 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 * https://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.netty5.util.internal;
17
18 import io.netty5.util.Resource;
19 import io.netty5.util.concurrent.Promise;
20 import io.netty5.util.internal.ObjectPool.Handle;
21
22 /**
23 * Some pending write which should be picked up later.
24 */
25 public final class PendingWrite {
26 private static final ObjectPool<PendingWrite> RECYCLER = ObjectPool.newPool(PendingWrite::new);
27
28 /**
29 * Create a new empty {@link RecyclableArrayList} instance
30 */
31 public static PendingWrite newInstance(Object msg, Promise<Void> promise) {
32 PendingWrite pending = RECYCLER.get();
33 pending.msg = msg;
34 pending.promise = promise;
35 return pending;
36 }
37
38 private final Handle<PendingWrite> handle;
39 private Object msg;
40 private Promise<Void> promise;
41
42 private PendingWrite(Handle<PendingWrite> handle) {
43 this.handle = handle;
44 }
45
46 /**
47 * Clear and recycle this instance.
48 */
49 public boolean recycle() {
50 msg = null;
51 promise = null;
52 handle.recycle(this);
53 return true;
54 }
55
56 /**
57 * Fails the underlying {@link Promise} with the given cause and recycle this instance.
58 */
59 public boolean failAndRecycle(Throwable cause) {
60 Resource.dispose(msg);
61 if (promise != null) {
62 promise.setFailure(cause);
63 }
64 return recycle();
65 }
66
67 /**
68 * Mark the underlying {@link Promise} successfully and recycle this instance.
69 */
70 public boolean successAndRecycle() {
71 if (promise != null) {
72 promise.setSuccess(null);
73 }
74 return recycle();
75 }
76
77 public Object msg() {
78 return msg;
79 }
80
81 public Promise<Void> promise() {
82 return promise;
83 }
84
85 /**
86 * Recycle this instance and return the {@link Promise}.
87 */
88 public Promise<Void> recycleAndGet() {
89 Promise<Void> promise = this.promise;
90 recycle();
91 return promise;
92 }
93 }