]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/src/org/argeo/util/ServiceChannel.java
1 package org
.argeo
.util
;
3 import java
.io
.IOException
;
4 import java
.nio
.ByteBuffer
;
5 import java
.nio
.channels
.AsynchronousByteChannel
;
6 import java
.nio
.channels
.CompletionHandler
;
7 import java
.nio
.channels
.ReadableByteChannel
;
8 import java
.nio
.channels
.WritableByteChannel
;
9 import java
.util
.concurrent
.ExecutorService
;
10 import java
.util
.concurrent
.Future
;
12 /** An {@link AsynchronousByteChannel} based on an {@link ExecutorService}. */
13 public class ServiceChannel
implements AsynchronousByteChannel
{
14 private final ReadableByteChannel in
;
15 private final WritableByteChannel out
;
17 private boolean open
= true;
19 private ExecutorService executor
;
21 public ServiceChannel(ReadableByteChannel in
, WritableByteChannel out
, ExecutorService executor
) {
24 this.executor
= executor
;
28 public Future
<Integer
> read(ByteBuffer dst
) {
29 return executor
.submit(() -> in
.read(dst
));
33 public <A
> void read(ByteBuffer dst
, A attachment
, CompletionHandler
<Integer
, ?
super A
> handler
) {
35 Future
<Integer
> res
= read(dst
);
36 handler
.completed(res
.get(), attachment
);
37 } catch (Exception e
) {
38 handler
.failed(e
, attachment
);
43 public Future
<Integer
> write(ByteBuffer src
) {
44 return executor
.submit(() -> out
.write(src
));
48 public <A
> void write(ByteBuffer src
, A attachment
, CompletionHandler
<Integer
, ?
super A
> handler
) {
50 Future
<Integer
> res
= write(src
);
51 handler
.completed(res
.get(), attachment
);
52 } catch (Exception e
) {
53 handler
.failed(e
, attachment
);
58 public synchronized void close() throws IOException
{
61 } catch (Exception e
) {
66 } catch (Exception e
) {
74 public synchronized boolean isOpen() {