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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
| public class ImageProcessingService extends ImageServiceGrpc.ImageServiceImplBase {
private final ExecutorService processingExecutor; private final Semaphore processingSemaphore; private static final int MAX_QUEUE_SIZE = 100; public enum ResponseMode { STREAMING, BATCHED } private final ResponseMode responseMode;
public ImageProcessingService(int maxConcurrentImages, ResponseMode mode) { this.responseMode = mode; this.processingExecutor = new ThreadPoolExecutor( Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 2, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new ThreadFactory() { private int counter = 0; @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, "image-processor-" + counter++); thread.setDaemon(true); return thread; } }, new ThreadPoolExecutor.CallerRunsPolicy() ); this.processingSemaphore = new Semaphore(maxConcurrentImages); }
@Override public StreamObserver<ImageChunk> processImages(StreamObserver<Response> responseObserver) { if (responseMode == ResponseMode.STREAMING) { return new StreamingImageChunkObserver(responseObserver); } else { return new BatchedImageChunkObserver(responseObserver); } }
private class StreamingImageChunkObserver implements StreamObserver<ImageChunk> { protected final StreamObserver<Response> responseObserver; protected final Queue<ImageChunk> chunkQueue = new ArrayDeque<>(); protected final AtomicBoolean isProcessing = new AtomicBoolean(false); protected ImageAssembler currentImageAssembler;
public StreamingImageChunkObserver(StreamObserver<Response> responseObserver) { this.responseObserver = responseObserver; this.currentImageAssembler = new ImageAssembler(); }
@Override public void onNext(ImageChunk chunk) { synchronized (chunkQueue) { while (chunkQueue.size() >= MAX_QUEUE_SIZE) { try { chunkQueue.wait(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } chunkQueue.add(chunk); chunkQueue.notify(); }
if (isProcessing.compareAndSet(false, true)) { processingExecutor.execute(this::processQueue); } }
@Override public void onError(Throwable t) { responseObserver.onError(t); cleanup(); }
@Override public void onCompleted() { synchronized (chunkQueue) { chunkQueue.add(new ImageChunk().setIsLast(true).setIndex(-1)); chunkQueue.notify(); } }
protected void processQueue() { try { while (true) { ImageChunk chunk; synchronized (chunkQueue) { while (chunkQueue.isEmpty()) { chunkQueue.wait(); } chunk = chunkQueue.poll(); chunkQueue.notify(); }
if (chunk.getIsLast()) { if (currentImageAssembler.hasChunks()) { processCurrentImage(); } responseObserver.onCompleted(); cleanup(); return; }
if (chunk.getIndex() < 0) { currentImageAssembler.addChunk(chunk); processCurrentImage(); currentImageAssembler = new ImageAssembler(); } else { currentImageAssembler.addChunk(chunk); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); responseObserver.onError(e); } catch (Exception e) { responseObserver.onError(e); } finally { isProcessing.set(false); } }
protected void processCurrentImage() throws InterruptedException { processingSemaphore.acquire(); byte[] imageData = currentImageAssembler.getImageData(); ImageChunk firstChunk = currentImageAssembler.getFirstChunk(); currentImageAssembler.clear(); processingExecutor.execute(() -> { try { Response response = processImage(imageData, firstChunk); responseObserver.onNext(response); } catch (Exception e) { responseObserver.onError(e); } finally { processingSemaphore.release(); } }); }
protected void cleanup() { synchronized (chunkQueue) { chunkQueue.clear(); } isProcessing.set(false); if (currentImageAssembler != null) { currentImageAssembler.clear(); currentImageAssembler = null; } } }
private class BatchedImageChunkObserver extends StreamingImageChunkObserver { private final Queue<Response> responseQueue = new ConcurrentLinkedQueue<>(); public BatchedImageChunkObserver(StreamObserver<Response> responseObserver) { super(responseObserver); } @Override protected void processCurrentImage() throws InterruptedException { processingSemaphore.acquire(); byte[] imageData = currentImageAssembler.getImageData(); ImageChunk firstChunk = currentImageAssembler.getFirstChunk(); currentImageAssembler.clear(); processingExecutor.execute(() -> { try { Response response = processImage(imageData, firstChunk); responseQueue.add(response); } catch (Exception e) { responseObserver.onError(e); } finally { processingSemaphore.release(); } }); } @Override protected void processQueue() { try { super.processQueue(); Response batchResponse = Response.newBuilder() .addAllResponses(responseQueue) .build(); responseObserver.onNext(batchResponse); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(e); } } }
private static class ImageAssembler { private final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); private ImageChunk firstChunk;
public void addChunk(ImageChunk chunk) { if (firstChunk == null) { firstChunk = chunk; } byteStream.write(chunk.getData().toByteArray()); }
public byte[] getImageData() { return byteStream.toByteArray(); }
public ImageChunk getFirstChunk() { return firstChunk; }
public boolean hasChunks() { return firstChunk != null; } public void clear() { byteStream.reset(); firstChunk = null; } }
private Response processImage(byte[] data, ImageChunk firstChunk) { return Response.newBuilder().build(); } }
|