SlideShare a Scribd company logo
Everything You Wanted to
Know
About Writing Async,
Concurrent HTTP Apps in Java
Agenda
• Mostly this:
Agenda
• And this:
Agenda
• And this:
About your speaker
linkd.in/jbaruch
stackoverflow.com/users/402053/jbaruch
What Frog?
What Frog?
What Frog?
What Frog?
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Requirements
– parallel file Downloads
– Parallel file parts
– interrupt/pause/resume
– Progress events
– Checksums caching
First Association for “concurrent
downloader”
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Lucky day: Download manager
written in Java!
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Let’s look if we can use it!
1. No traceable license
2. No website or docs
3. No traceable sources
4. It’s an app, not a lib
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Java.net.urlconnection
1. Memory wasteful (buffering)
2. Minimal API
3. Blocking streams
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
What we’re looking for
1. Async/non-blocking
2. Event callbacks
What is IT going to take
1. Reactor
2. nio
Welcome to the reactor
– pattern for lightweight concurrency
– Event driven
– Threads reuse
– Uses non-blocking Io
Original pattern
http://www.dre.vanderbilt.edu/~schmidt/PDF/reactor-siemens.pdf
Guess the author by the
diagram
http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf
In Java, Reactor
means NIO
Selector as a multiplexer
Java version - Registering
SocketChannel channel= SocketChannel.open();
socketChannel.connect(new
InetSocketAddress("http://remote.com", 80));
...
Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey k = channel.register(selector,
SelectionKey.OP_READ);
k.attach(handler);
Java version - Dispatcher
while (!Thread.interrupted()) {
selector.select();
Set selected = selector.selectedKeys();
Iterator it = selected.iterator();
while (it.hasNext())
SelectionKey k = (SelectionKey)(it.next();
((Runnable)(k.attachment())).run();
selected.clear();
}
Handling reactor events is complex
– Need to maintain state
– Buffering – assembling chunks
– Coordinating async events
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Nio libraries
– Most of them are servers
–Netty, grizzly, etc.
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
Nio libraries
– Most of them are servers
–Netty, grizzly, etc.
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
– Client and server nio library
– Evolved from netty
– Latest release October 2012
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Nio libraries
– Most of them are servers
–Netty, grizzly, etc
– Apache Mina
– Apache HTTP components asyncclient
– Ning http client
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Ning’s async http client
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Here it is!
try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) {
ListenableFuture<Response> future = asyncHttpClient.prepareGet(
"http://oss.jfrog.org/api/system/ping").execute(
new AsyncCompletionHandler<Response>() {
@Override
public Response onCompleted(Response response) {
System.out.println(response.getResponseBody());
return response;
}
@Override
public void onThrowable(Throwable t) {
t.printStackTrace();
}
});
Response response = future.get();
}
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
HAC Concepts
– Request producer
– Response consumer
try (CloseableHttpAsyncClient asyncHttpClient = HttpAsyncClients.createDefault()) {
asyncHttpClient.start();
Future<HttpResponse> future = asyncHttpClient.execute(
HttpAsyncMethods.createGet("http://oss.jfrog.org/api/system/ping"),
new AsyncByteConsumer<HttpResponse>() {
@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println(response.getStatusLine().getReasonPhrase());
}
@Override
protected void onByteReceived(final CharBuffer buf, final IOControl ioctrl) { }
@Override
protected void releaseResources() { }
@Override
protected HttpResponse buildResult(final HttpContext context) {
return (HttpResponse) context.getAttribute("http.response");
}
}, null);
HttpResponse response = future.get();
}
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Choosing between ning and http
asyncclient
"All problems in computer science can
be solved by another level of
indirection"
David
Wheeler
public interface HttpProviderDownloadHandler {
void onResponseReceived(int statusCode, Map<String, List<String>> headers);
boolean onBytesReceived(ByteBuffer buf);
void onFailed(Throwable error);
void onCanceled();
void onCompleted();
}
Head to head
Feature/Library Ning client Http Async Client
Maturity Good Very new (early 2014)
Download cancelation Easy With bugs
Progress hooks Events not granular
enough
Just use onByteReceived()
Documentation A bit sparse Minimal
Server-side counterpart None, client only org.apache.httpcomponents
httpcore-nio
Performance?
0
100
200
300
400
500
600
700
800
900
Small file Medium file Large file
Ning
AHAC
http://blogs.atlassian.com/2013/07/http-client-performance-io/
Rfc2616: a universe of its own
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Confused?
Just read some stackoverflow
(and improve your rep as you go)
And that one for
discovering that
range header is
lost on redirect
Question!
What should be
content-length
when using
compression?
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
https://github.com/http2/http2-spec/issues/46
Question!
Why when redirected to CDN
all the chunks start from zero?
HttpAsyncClientBuilder builder = HttpAsyncClients.custom();
// add redirect strategy that copies "range" headers, if exist
builder.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
HttpContext context)
HttpUriRequest redirectRequest = super.getRedirect(request, response, context);
// copy "Range" headers, if exist
Header[] rangeHeaders = request.getHeaders(HttpHeaders.RANGE);
if (rangeHeaders != null) {
for (Header header : rangeHeaders) {
redirectRequest.addHeader(header);
}
}
return redirectRequest;
}});
Question!
How many simultaneous
connections should I open?
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Question!
What’s wrong
with the
following
code?
public static String encodeUrl(String urlStr) {
URLEncoder.encode(urlStr, "UTF-8");
...
}
Decoded URLs cannot be
re-encoded to the same form
http://example.com/?query=a&b==c
Cannot be decoded back after it was
encoded:
http://example.com/?query=a%26b==c
Don’t use java.net.URLEncoder
“Utility class for HTML form encoding.
This class contains static methods for
converting a String to the
application/x-www-form-
urlencoded MIME format.
For more information about HTML
form encoding, consult the HTML
specification.”
AHC Alternatives
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Question!
How do I
close a
socket
correctly?
How hard can it be to close a
socket?
The art of socket closing
http://www.safaribooksonline.com/library/view/http-the-definitive/1565925092/ch04s07.html
Half-closed: no new customers
Never block in socket close()
• The other side expects you
to clean up nicely
• It will give up on time out
• You will wait (forever)
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Remember?
Question!
How can I write
file parts
concurrently?
– Write to separate files, combine on finish
– Write to same file, seeking to the right
position
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask
Use FileChannel
• Implements SeekableByteChannel
java.nio.channels.FileChannel#write(
java.nio.ByteBuffer src, long position)
Download progress tracking
• PersistentFileProgressInfo
– Save the total size, sha1, number of parts
– State of each part (offset, size, completed...)
FileProgressInfo FilePartProgressInfo
*
File Locking
File locking Levels
– VM level
– OS level
OS level File locking
• Multiple downloader instances writing to
the same file
• Needed for writing:
– Partial download file
– Persistent download progress
FileLock lock = fileChannel.tryLock();
//Non-shared: (0L, Long.MAX_VALUE, false)
if (lock == null) {
throw new OverlappingFileLockException();
}
return lock;
}
OS Level File Locking -
Exclusive
private FileLock lock(FileChannel fileChannel) throws IOException {
FileLock lock = fileChannel.tryLock(Long.MAX_VALUE - 1, 1, false);
if (lock == null) {
throw new OverlappingFileLockException();
}
return lock;
}
OS Level File Locking –
Advisory exclusive
WTF?!
VM Level File Locking
VM Level File Locking
– Prevent same VM threads writing to the file when we
started closing it
– Closing sequence:
– Release file locks
– Close channels
– Rename a file to it's final name (remove .part)
– Erase progress info
VM Level File Locking
ReentrantReadWriteLock.ReadLock writeToFileLock = rwl.readLock();
ReentrantReadWriteLock.WriteLock closeFileLock = rwl.writeLock();
public void close() throws IOException {
this.closeFileLock.lock();
}
public int write(int partIndex, ByteBuffer buf) {
if (!this.writeToFileLock.tryLock()) {
throw new IllegalStateException("File is being closed");
}
...
}
What’s next?
http/2
– Mostly standardizing Google's spdy
– Header compression
– multiplexing
– Prioritization
– Server push
– On the way clear some stuff
– E.g. compressed content length
Ease the load
Links!
• RTFM: RFC 2616
• Ultimate book: HTTP: The Definitive
Guide
– Amazon
– Safari
• Reactor pattern
• Doug Lea on NIO
No, Thank you!

More Related Content

PPTX
Everything you wanted to know about writing async, concurrent http apps in java
PDF
Reactive Programming with Rx
KEY
PyCon AU 2012 - Debugging Live Python Web Applications
PDF
Tornado Web Server Internals
PDF
Advanced VCL: how to use restart
PDF
About Node.js
PPTX
Solving anything in VCL
PDF
On Centralizing Logs
Everything you wanted to know about writing async, concurrent http apps in java
Reactive Programming with Rx
PyCon AU 2012 - Debugging Live Python Web Applications
Tornado Web Server Internals
Advanced VCL: how to use restart
About Node.js
Solving anything in VCL
On Centralizing Logs

What's hot (20)

PPTX
A complete guide to Node.js
PDF
Programming language for the cloud infrastructure
PDF
Tornado in Depth
PDF
Reactive server with netty
PDF
VCL template abstraction model and automated deployments to Fastly
PDF
LogStash - Yes, logging can be awesome
PDF
An Introduction to Tornado
PDF
Tornadoweb
PPTX
Python, async web frameworks, and MongoDB
PDF
Introduction tomcat7 servlet3
PDF
Beyond Breakpoints: A Tour of Dynamic Analysis
KEY
PyCon US 2012 - State of WSGI 2
KEY
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PDF
I can't believe it's not a queue: Kafka and Spring
ZIP
Nginx + Tornado = 17k req/s
PPTX
Tornado - different Web programming
PDF
Nodejs Explained with Examples
PPTX
How NOT to write in Node.js
PPTX
Tornado web
PPTX
Node.js - Advanced Basics
A complete guide to Node.js
Programming language for the cloud infrastructure
Tornado in Depth
Reactive server with netty
VCL template abstraction model and automated deployments to Fastly
LogStash - Yes, logging can be awesome
An Introduction to Tornado
Tornadoweb
Python, async web frameworks, and MongoDB
Introduction tomcat7 servlet3
Beyond Breakpoints: A Tour of Dynamic Analysis
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
I can't believe it's not a queue: Kafka and Spring
Nginx + Tornado = 17k req/s
Tornado - different Web programming
Nodejs Explained with Examples
How NOT to write in Node.js
Tornado web
Node.js - Advanced Basics
Ad

Similar to Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask (20)

PPTX
Async programming and python
PPT
JS everywhere 2011
PDF
Introduction to Apache Beam
PDF
Introduction to Node.js
PDF
Logging for Production Systems in The Container Era
PPTX
Binary Studio Academy: Concurrency in C# 5.0
PDF
Webscraping with asyncio
PPTX
Node.js Workshop - Sela SDP 2015
PDF
Infinit filesystem, Reactor reloaded
PDF
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
PPT
nodejs_at_a_glance, understanding java script
PPTX
introduction to node.js
PPT
nodejs_at_a_glance.ppt
PPT
Node.js: CAMTA Presentation
KEY
Node.js - A practical introduction (v2)
PPT
AsyncIO To Speed Up Your Crawler
PDF
Service workers
ODP
Asynchronous I/O in NodeJS - new standard or challenges?
PDF
What`s new in Java 7
PPSX
Async-await best practices in 10 minutes
Async programming and python
JS everywhere 2011
Introduction to Apache Beam
Introduction to Node.js
Logging for Production Systems in The Container Era
Binary Studio Academy: Concurrency in C# 5.0
Webscraping with asyncio
Node.js Workshop - Sela SDP 2015
Infinit filesystem, Reactor reloaded
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
nodejs_at_a_glance, understanding java script
introduction to node.js
nodejs_at_a_glance.ppt
Node.js: CAMTA Presentation
Node.js - A practical introduction (v2)
AsyncIO To Speed Up Your Crawler
Service workers
Asynchronous I/O in NodeJS - new standard or challenges?
What`s new in Java 7
Async-await best practices in 10 minutes
Ad

More from Baruch Sadogursky (20)

PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
PDF
Data driven devops as presented at QCon London 2018
PDF
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
PDF
Java Puzzlers NG S03 a DevNexus 2018
PDF
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
PDF
Data driven devops as presented at Codemash 2018
PDF
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
PPTX
Best Practices for Managing Docker Versions as presented at JavaOne 2017
PDF
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
PPTX
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
PDF
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsbu...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
PDF
Let’s Wing It: A Study in DevRel Strategy
PDF
Log Driven First Class Customer Support at Scale
PPTX
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
PDF
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
Data driven devops as presented at QCon London 2018
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
Java Puzzlers NG S03 a DevNexus 2018
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
Data driven devops as presented at Codemash 2018
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
Best Practices for Managing Docker Versions as presented at JavaOne 2017
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsbu...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
Let’s Wing It: A Study in DevRel Strategy
Log Driven First Class Customer Support at Scale
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...

Recently uploaded (20)

PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Big Data Technologies - Introduction.pptx
PPTX
1. Introduction to Computer Programming.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
Tartificialntelligence_presentation.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Encapsulation theory and applications.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Getting Started with Data Integration: FME Form 101
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Spectroscopy.pptx food analysis technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Big Data Technologies - Introduction.pptx
1. Introduction to Computer Programming.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Network Security Unit 5.pdf for BCA BBA.
Tartificialntelligence_presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
MIND Revenue Release Quarter 2 2025 Press Release
Encapsulation theory and applications.pdf
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
A comparative analysis of optical character recognition models for extracting...
Per capita expenditure prediction using model stacking based on satellite ima...
Getting Started with Data Integration: FME Form 101

Presentation: Everything you wanted to know about writing async, high-concurrency HTTP applications in Java, but were afraid to ask

Editor's Notes

  • #3: Things that are not simple
  • #4: Why you dont’s
  • #5: Just avoid
  • #6: CURRENT – JB NEXT - YOAV
  • #27: Events are multiplexed by a single thread dispatcher
  • #53: TODO send table to back!!!
  • #55: Hypertext Transfer Protocol -- HTTP/1.1
  • #67: RFC2616 8.1.4
  • #68: Browsers go like:
  • #87: RAC is not concurrent!
  • #94: lock beyond the end of file, so we can write while others are reading avoid OS-dependent no support for shared lock (for concurrent r/w) and fallback to exclusive + avoid OS-dependent access effect of exclusive locks (Windoze...) Allows writing and reading by knowing if someone else is writing https://community.oracle.com/message/8781694