1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http.impl.io;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.net.Socket;
34 import java.util.concurrent.atomic.AtomicReference;
35
36 import org.apache.hc.core5.util.Args;
37
38
39
40
41
42
43
44 public class SocketHolder {
45
46 private final Socket socket;
47 private final AtomicReference<InputStream> inputStreamRef;
48 private final AtomicReference<OutputStream> outputStreamRef;
49
50 public SocketHolder(final Socket socket) {
51 this.socket = Args.notNull(socket, "Socket");
52 this.inputStreamRef = new AtomicReference<>();
53 this.outputStreamRef = new AtomicReference<>();
54 }
55
56 public final Socket getSocket() {
57 return socket;
58 }
59
60 public final InputStream getInputStream() throws IOException {
61 InputStream local = inputStreamRef.get();
62 if (local != null) {
63 return local;
64 }
65 local = getInputStream(socket);
66 if (inputStreamRef.compareAndSet(null, local)) {
67 return local;
68 }
69 return inputStreamRef.get();
70 }
71
72 protected InputStream getInputStream(final Socket socket) throws IOException {
73 return socket.getInputStream();
74 }
75
76 protected OutputStream getOutputStream(final Socket socket) throws IOException {
77 return socket.getOutputStream();
78 }
79
80 public final OutputStream getOutputStream() throws IOException {
81 OutputStream local = outputStreamRef.get();
82 if (local != null) {
83 return local;
84 }
85 local = getOutputStream(socket);
86 if (outputStreamRef.compareAndSet(null, local)) {
87 return local;
88 }
89 return outputStreamRef.get();
90 }
91
92 @Override
93 public String toString() {
94 return socket.toString();
95 }
96
97 }