Skip to content

Commit 35d58fc

Browse files
committed
#12681 atomically retain the buffer with a check that it still is in the cache, otherwise delegate to the wrapped content
Signed-off-by: Ludovic Orban <[email protected]>
1 parent 14d7a68 commit 35d58fc

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

jetty-core/jetty-http/src/main/java/org/eclipse/jetty/http/content/CachingHttpContentFactory.java

+24-4
Original file line numberDiff line numberDiff line change
@@ -354,19 +354,39 @@ public String getKey()
354354
@Override
355355
public void writeTo(Content.Sink sink, long offset, long length, Callback callback)
356356
{
357+
boolean retained = false;
357358
try
358359
{
359-
_buffer.retain();
360-
sink.write(true, BufferUtil.slice(_buffer.getByteBuffer(), (int)offset, (int)length), Callback.from(_buffer::release, callback));
360+
retained = retain();
361+
if (retained)
362+
sink.write(true, BufferUtil.slice(_buffer.getByteBuffer(), Math.toIntExact(offset), Math.toIntExact(length)), Callback.from(this::release, callback));
363+
else
364+
getWrapped().writeTo(sink, offset, length, callback);
361365
}
362366
catch (Throwable x)
363367
{
364-
// BufferUtil.slice() may fail if offset and/or length are out of bounds.
365-
_buffer.release();
368+
// BufferUtil.slice() may fail if offset and/or length are out of bounds,
369+
// Math.toIntExact may fail too if offset or length are > Integer.MAX_VALUE.
370+
if (retained)
371+
release();
366372
callback.failed(x);
367373
}
368374
}
369375

376+
/**
377+
* Atomically checks that this content still is in cache (so it hasn't been released yet and is still usable) and retain
378+
* its internal buffer if it is.
379+
* @return true if this content can be used and has been retained, false otherwise.
380+
*/
381+
private boolean retain()
382+
{
383+
return _cache.computeIfPresent(_cacheKey, (s, cachingHttpContent) ->
384+
{
385+
_buffer.retain();
386+
return cachingHttpContent;
387+
}) != null;
388+
}
389+
370390
@Override
371391
public void release()
372392
{

0 commit comments

Comments
 (0)