blob: ab03f282c33848dd2301a640b3b6a985ff7dc434 (
plain) (
blame)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;
import java.util.Objects;
/**
* <p>This class provides a blocking <em>write</em>-interface to a {@link ContentChannel}. Both {@link
* #write(ByteBuffer)} and {@link #close()} methods provide an internal {@link CompletionHandler} to the decorated
* {@link ContentChannel} calls, and wait for these to be called before returning. If {@link
* CompletionHandler#failed(Throwable)} is called, the corresponding Throwable is thrown to the caller.</p>
*
* @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen</a>
* @see FastContentWriter
*/
public final class BlockingContentWriter {
private final ContentChannel channel;
/**
* <p>Creates a new BlockingContentWriter that encapsulates a given {@link ContentChannel}.</p>
*
* @param content The ContentChannel to encapsulate.
* @throws NullPointerException If the <em>content</em> argument is null.
*/
public BlockingContentWriter(ContentChannel content) {
Objects.requireNonNull(content, "content");
this.channel = content;
}
/**
* <p>Writes to the underlying {@link ContentChannel} and waits for the operation to complete.</p>
*
* @param buf The ByteBuffer to write.
* @throws InterruptedException If the thread was interrupted while waiting.
* @throws RuntimeException If the operation failed to complete, see cause for details.
*/
public void write(ByteBuffer buf) throws InterruptedException {
try {
FutureCompletion future = new FutureCompletion();
channel.write(buf, future);
future.get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
if (t instanceof Error) {
throw (Error)t;
}
throw new RuntimeException(t);
}
}
/**
* <p>Closes the underlying {@link ContentChannel} and waits for the operation to complete.</p>
*
* @throws InterruptedException If the thread was interrupted while waiting.
* @throws RuntimeException If the operation failed to complete, see cause for details.
*/
public void close() throws InterruptedException {
try {
FutureCompletion future = new FutureCompletion();
channel.close(future);
future.get();
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException)t;
}
if (t instanceof Error) {
throw (Error)t;
}
throw new RuntimeException(t);
}
}
}
|