1/* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package libcore.java.nio.channels; 18 19import java.nio.channels.CompletionHandler; 20 21/** A CompletionHandler that behaves like a Future and enables compact, single-threaded tests. */ 22public class FutureLikeCompletionHandler<V> implements CompletionHandler<V, Object> { 23 Throwable e; 24 boolean done; 25 V result; 26 Object attachment; 27 28 public void completed(V result, Object attachment) { 29 synchronized (this) { 30 if (done) { 31 e = new IllegalStateException("CompletionHandler used twice"); 32 } 33 this.result = result; 34 this.done = true; 35 this.attachment = attachment; 36 this.notifyAll(); 37 } 38 } 39 40 public void failed(Throwable exc, Object attachment) { 41 synchronized (this) { 42 if (done) { 43 e = new IllegalStateException("CompletionHandler used twice"); 44 } 45 this.e = exc; 46 this.done = true; 47 this.attachment = attachment; 48 this.notifyAll(); 49 } 50 } 51 52 V get(long timeoutMiliseconds) throws Throwable { 53 synchronized (this) { 54 while (!done) { 55 wait(timeoutMiliseconds); 56 } 57 if (e != null) { 58 throw e; 59 } 60 return result; 61 } 62 } 63 64 public Object getAttachment() { 65 synchronized (this) { 66 return attachment; 67 } 68 } 69} 70