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?
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Requirements 
– parallel file Downloads 
– Parallel file parts 
– interrupt/pause/resume 
– Progress events 
– Checksums caching
First Association for “concurrent 
downloader”
Everything you wanted to know about writing async, concurrent http apps in java
Lucky day: Download manager 
written in java!
Everything you wanted to know about writing async, concurrent http apps in java
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
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Java.net.urlconnection 
1. Memory wasteful (buffering) 
2. Minimal API 
3. Blocking streams
Everything you wanted to know about writing async, concurrent http apps in java
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
Everything you wanted to know about writing async, concurrent http apps in java
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
Everything you wanted to know about writing async, concurrent http apps in java
Nio libraries 
– Most of them are servers 
–Netty, grizzly, etc 
– Apache Mina 
– Apache HTTP components asyncclient 
– Ning http client
Everything you wanted to know about writing async, concurrent http apps in java
Ning’s async http client
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
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(); 
}
Everything you wanted to know about writing async, concurrent http apps in java
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();	 
}
Everything you wanted to know about writing async, concurrent http apps in java
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? 
900 
800 
700 
600 
500 
400 
300 
200 
100 
0 
Small file Medium file Large file 
Ning 
AHAC 
http://blogs.atlassian.com/2013/07/http-client-performance-io/
Rfc2616: a universe of its own
Everything you wanted to know about writing async, concurrent http apps in java
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?
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
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?
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
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
Everything you wanted to know about writing async, concurrent http apps in java
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)
Everything you wanted to know about writing async, concurrent http apps in java
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
Everything you wanted to know about writing async, concurrent http apps in java
Everything you wanted to know about writing async, concurrent http apps in java
USE FileChannel 
• Implements SeekableByteChannel 
java.nio.channels.FileChannel#write( 
java.nio.ByteBuffer src, long position)
download progress tracking 
* 
FileProgressInfo FilePartProgressInfo 
• PersistentFileProgressInfo 
– Save the total size, sha1, number of parts 
– State of each part (offset, size, completed...)
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

What's hot (20)

PPTX
The tale of 100 cve's
Prajal Kulkarni
 
PDF
Programming language for the cloud infrastructure
Yaroslav Muravskyi
 
PDF
About Node.js
Artemisa Yescas Engler
 
PDF
I can't believe it's not a queue: Kafka and Spring
Joe Kutner
 
KEY
Time tested php with libtimemachine
Nick Galbreath
 
PDF
Tornado in Depth
Òscar Vilaplana
 
PPTX
A complete guide to Node.js
Prabin Silwal
 
PDF
Tornadoweb
Osman Yuksel
 
PDF
On Centralizing Logs
Sematext Group, Inc.
 
PDF
An Introduction to Tornado
Gavin Roy
 
PPTX
How NOT to write in Node.js
Piotr Pelczar
 
PPTX
Python, async web frameworks, and MongoDB
emptysquare
 
PPTX
Node.js - Advanced Basics
Doug Jones
 
PDF
Bulding a reactive game engine with Spring 5 & Couchbase
Alex Derkach
 
KEY
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
PPTX
Tornado - different Web programming
Dima Malenko
 
ZIP
Nginx + Tornado = 17k req/s
moret1979
 
KEY
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
Graham Dumpleton
 
PDF
Nodejs Explained with Examples
Gabriele Lana
 
PDF
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 
The tale of 100 cve's
Prajal Kulkarni
 
Programming language for the cloud infrastructure
Yaroslav Muravskyi
 
About Node.js
Artemisa Yescas Engler
 
I can't believe it's not a queue: Kafka and Spring
Joe Kutner
 
Time tested php with libtimemachine
Nick Galbreath
 
Tornado in Depth
Òscar Vilaplana
 
A complete guide to Node.js
Prabin Silwal
 
Tornadoweb
Osman Yuksel
 
On Centralizing Logs
Sematext Group, Inc.
 
An Introduction to Tornado
Gavin Roy
 
How NOT to write in Node.js
Piotr Pelczar
 
Python, async web frameworks, and MongoDB
emptysquare
 
Node.js - Advanced Basics
Doug Jones
 
Bulding a reactive game engine with Spring 5 & Couchbase
Alex Derkach
 
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
Tornado - different Web programming
Dima Malenko
 
Nginx + Tornado = 17k req/s
moret1979
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
Graham Dumpleton
 
Nodejs Explained with Examples
Gabriele Lana
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Fastly
 

Viewers also liked (16)

PPTX
Async and Await on the Server
Doug Jones
 
PPTX
From Callback Hell to Async Heaven - Promises!
Gil Tayar
 
PPTX
Sync with async
prabathsl
 
PDF
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv Startup Club
 
PDF
How to meets Async and Task
Kouji Matsui
 
PDF
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Hans-Gunther Schmidt
 
PDF
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
PPT
Multithreading, Blocking IO and Async IO
Directi Group
 
PDF
Async await...oh wait!
Thomas Pierrain
 
PDF
Netty: asynchronous data transfer
Victor Cherkassky
 
ODP
Servlet 3.1 Async I/O
Simone Bordet
 
PDF
Sync async-blocking-nonblocking-io
Cheoloh Bae
 
PPTX
Angular 2 어디까지 왔을까
장현 한
 
PPTX
Think Async in Java 8
Dmitry Alexandrov
 
PDF
Syncing Async
FITC
 
PDF
A Research Study into DevOps Bottlenecks
Baruch Sadogursky
 
Async and Await on the Server
Doug Jones
 
From Callback Hell to Async Heaven - Promises!
Gil Tayar
 
Sync with async
prabathsl
 
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv Startup Club
 
How to meets Async and Task
Kouji Matsui
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Hans-Gunther Schmidt
 
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Multithreading, Blocking IO and Async IO
Directi Group
 
Async await...oh wait!
Thomas Pierrain
 
Netty: asynchronous data transfer
Victor Cherkassky
 
Servlet 3.1 Async I/O
Simone Bordet
 
Sync async-blocking-nonblocking-io
Cheoloh Bae
 
Angular 2 어디까지 왔을까
장현 한
 
Think Async in Java 8
Dmitry Alexandrov
 
Syncing Async
FITC
 
A Research Study into DevOps Bottlenecks
Baruch Sadogursky
 
Ad

Similar to Everything you wanted to know about writing async, concurrent http apps in java (20)

PPT
A java servers
vibrantuser
 
PDF
A java servers
vibrantuser
 
DOCX
692015 programming assignment 1 building a multi­threaded w
smile790243
 
DOCX
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
 
PDF
How do I - Networking and Webservices - Transcript.pdf
ShaiAlmog1
 
PDF
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
PDF
CON5898 What Servlet 4.0 Means To You
Edward Burns
 
PPT
Scmad Chapter09
Marcel Caraciolo
 
PPTX
computer network introduction. psc notes . Assisant professor in cse.
bushraphd2022
 
PDF
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
PDF
Revisiting HTTP/2
Fastly
 
PDF
Httpcore tutorial
Aravindharamanan S
 
DOCX
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
 
PDF
A first look into the Project Loom in Java
Lukas Steinbrecher
 
PPTX
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
PPTX
Think async
Bhakti Mehta
 
PDF
Http Status Report
ConSanFrancisco123
 
PPTX
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
Andreas Jakl
 
DOCX
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
 
KEY
What's up with HTTP?
Mark Nottingham
 
A java servers
vibrantuser
 
A java servers
vibrantuser
 
692015 programming assignment 1 building a multi­threaded w
smile790243
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
 
How do I - Networking and Webservices - Transcript.pdf
ShaiAlmog1
 
Non Blocking I/O for Everyone with RxJava
Frank Lyaruu
 
CON5898 What Servlet 4.0 Means To You
Edward Burns
 
Scmad Chapter09
Marcel Caraciolo
 
computer network introduction. psc notes . Assisant professor in cse.
bushraphd2022
 
Asynchronous, Event-driven Network Application Development with Netty
Ersin Er
 
Revisiting HTTP/2
Fastly
 
Httpcore tutorial
Aravindharamanan S
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
 
A first look into the Project Loom in Java
Lukas Steinbrecher
 
Asynchronous Web Programming with HTML5 WebSockets and Java
James Falkner
 
Think async
Bhakti Mehta
 
Http Status Report
ConSanFrancisco123
 
Java ME - 07 - Generic Connection Framework, HTTP and Sockets
Andreas Jakl
 
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
 
What's up with HTTP?
Mark Nottingham
 
Ad

More from Baruch Sadogursky (20)

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

Recently uploaded (20)

PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pdf
Varsha Nayak
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 

Everything you wanted to know about writing async, concurrent http apps in java

  • 1. Everything You Wanted to Know About Writing Async, Concurrent HTTP Apps in Java
  • 5. About your speaker linkd.in/jbaruch stackoverflow.com/users/402053/jbaruch
  • 12. Requirements – parallel file Downloads – Parallel file parts – interrupt/pause/resume – Progress events – Checksums caching
  • 13. First Association for “concurrent downloader”
  • 15. Lucky day: Download manager written in java!
  • 17. 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
  • 20. Java.net.urlconnection 1. Memory wasteful (buffering) 2. Minimal API 3. Blocking streams
  • 22. What we’re looking for 1. Async/non-blocking 2. Event callbacks
  • 23. What is IT going to take 1. Reactor 2. nio
  • 24. Welcome to the reactor
  • 25. – pattern for lightweight concurrency – Event driven – Threads reuse – Uses non-blocking Io
  • 27. Guess the author by the diagram http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf
  • 28. In Java, Reactor means NIO
  • 29. Selector as a multiplexer
  • 30. 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);
  • 31. 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(); }
  • 32. Handling reactor events is complex – Need to maintain state – Buffering – assembling chunks – Coordinating async events
  • 34. Nio libraries – Most of them are servers –Netty, grizzly, etc. – Apache Mina – Apache HTTP components asyncclient – Ning http client
  • 35. – Client and server nio library – Evolved from netty – Latest release October 2012
  • 37. Nio libraries – Most of them are servers –Netty, grizzly, etc – Apache Mina – Apache HTTP components asyncclient – Ning http client
  • 43. 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(); }
  • 45. HAC Concepts – Request producer – Response consumer
  • 46. 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(); }
  • 48. Choosing between ning and http asyncclient
  • 49. "All problems in computer science can be solved by another level of indirection" David Wheeler
  • 50. public interface HttpProviderDownloadHandler { void onResponseReceived(int statusCode, Map<String, List<String>> headers); boolean onBytesReceived(ByteBuffer buf); void onFailed(Throwable error); void onCanceled(); void onCompleted(); }
  • 51. 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
  • 52. Performance? 900 800 700 600 500 400 300 200 100 0 Small file Medium file Large file Ning AHAC http://blogs.atlassian.com/2013/07/http-client-performance-io/
  • 53. Rfc2616: a universe of its own
  • 56. Just read some stackoverflow (and improve your rep as you go)
  • 57. And that one for discovering that range header is lost on redirect
  • 58. Question! What should be content-length when using compression?
  • 62. Question! Why when redirected to CDN all the chunks start from zero?
  • 63. 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; }});
  • 64. Question! How many simultaneous connections should I open?
  • 69. Question! What’s wrong with the following code?
  • 70. public static String encodeUrl(String urlStr) { URLEncoder.encode(urlStr, "UTF-8"); ... }
  • 71. 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
  • 72. 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.”
  • 75. Question! How do I close a socket correctly?
  • 76. How hard can it be to close a socket?
  • 77. The art of socket closing http://www.safaribooksonline.com/library/view/http-the-definitive/1565925092/ch04s07.html
  • 78. Half-closed: no new customers
  • 79. 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)
  • 82. Question! How can I write file parts concurrently?
  • 83. – Write to separate files, combine on finish – Write to same file, seeking to the right position
  • 86. USE FileChannel • Implements SeekableByteChannel java.nio.channels.FileChannel#write( java.nio.ByteBuffer src, long position)
  • 87. download progress tracking * FileProgressInfo FilePartProgressInfo • PersistentFileProgressInfo – Save the total size, sha1, number of parts – State of each part (offset, size, completed...)
  • 89. File locking Levels – VM level – OS level
  • 90. OS level File locking • Multiple downloader instances writing to the same file • Needed for writing: – Partial download file – Persistent download progress
  • 91. FileLock lock = fileChannel.tryLock(); //Non-shared: (0L, Long.MAX_VALUE, false) if (lock == null) { throw new OverlappingFileLockException(); } return lock; } OS Level File Locking - Exclusive
  • 92. 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?!
  • 93. VM Level File Locking
  • 94. 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
  • 95. 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"); } ... }
  • 97. http/2 – Mostly standardizing Google's spdy – Header compression – multiplexing – Prioritization – Server push – On the way clear some stuff – E.g. compressed content length
  • 99. Links! • RTFM: RFC 2616 • Ultimate book: HTTP: The Definitive Guide – Amazon – Safari • Reactor pattern • Doug Lea on NIO

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
  • #52: TODO send table to back!!!
  • #54: Hypertext Transfer Protocol -- HTTP/1.1
  • #66: RFC2616 8.1.4
  • #67: Browsers go like:
  • #86: RAC is not concurrent!
  • #93: 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