SlideShare une entreprise Scribd logo
1  sur  100
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?
Requirements 
– parallel file Downloads 
– Parallel file parts 
– interrupt/pause/resume 
– Progress events 
– Checksums caching
First Association for “concurrent 
downloader”
Lucky day: Download manager 
written 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
Java.net.urlconnection 
1. Memory wasteful (buffering) 
2. Minimal API 
3. Blocking streams
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
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
Nio libraries 
– Most of them are servers 
–Netty, grizzly, etc 
– Apache Mina 
– Apache HTTP components asyncclient 
– Ning http client
Ning’s async http client
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(); 
}
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();	 
}
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
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?
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?
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
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)
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
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!

Contenu connexe

Tendances

Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
Òscar Vilaplana
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
Gavin Roy
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
Graham Dumpleton
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
Graham Dumpleton
 

Tendances (20)

The tale of 100 cve's
The tale of 100 cve'sThe tale of 100 cve's
The tale of 100 cve's
 
Programming language for the cloud infrastructure
Programming language for the cloud infrastructureProgramming language for the cloud infrastructure
Programming language for the cloud infrastructure
 
About Node.js
About Node.jsAbout Node.js
About Node.js
 
I can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and SpringI can't believe it's not a queue: Kafka and Spring
I can't believe it's not a queue: Kafka and Spring
 
Time tested php with libtimemachine
Time tested php with libtimemachineTime tested php with libtimemachine
Time tested php with libtimemachine
 
Tornado in Depth
Tornado in DepthTornado in Depth
Tornado in Depth
 
A complete guide to Node.js
A complete guide to Node.jsA complete guide to Node.js
A complete guide to Node.js
 
Tornadoweb
TornadowebTornadoweb
Tornadoweb
 
On Centralizing Logs
On Centralizing LogsOn Centralizing Logs
On Centralizing Logs
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
Python, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDBPython, async web frameworks, and MongoDB
Python, async web frameworks, and MongoDB
 
Node.js - Advanced Basics
Node.js - Advanced BasicsNode.js - Advanced Basics
Node.js - Advanced Basics
 
Bulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & CouchbaseBulding a reactive game engine with Spring 5 & Couchbase
Bulding a reactive game engine with Spring 5 & Couchbase
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Tornado - different Web programming
Tornado - different Web programmingTornado - different Web programming
Tornado - different Web programming
 
Nginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/sNginx + Tornado = 17k req/s
Nginx + Tornado = 17k req/s
 
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance TuningPyCon US 2012 - Web Server Bottlenecks and Performance Tuning
PyCon US 2012 - Web Server Bottlenecks and Performance Tuning
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Beyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic AnalysisBeyond Breakpoints: A Tour of Dynamic Analysis
Beyond Breakpoints: A Tour of Dynamic Analysis
 

En vedette

Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
Xamarin
 
Multithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IOMultithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IO
Directi Group
 
Syncing Async
Syncing AsyncSyncing Async
Syncing Async
FITC
 

En vedette (16)

Async and Await on the Server
Async and Await on the ServerAsync and Await on the Server
Async and Await on the Server
 
From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!From Callback Hell to Async Heaven - Promises!
From Callback Hell to Async Heaven - Promises!
 
Sync with async
Sync with  asyncSync with  async
Sync with async
 
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
Lviv MD Day 2015 Олексій Демедецький "Using Future for async flow application...
 
How to meets Async and Task
How to meets Async and TaskHow to meets Async and Task
How to meets Async and Task
 
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back AgainPromises And Chaining In AngularJS - Into Callback Hell And Back Again
Promises And Chaining In AngularJS - Into Callback Hell And Back Again
 
Using Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek SafarUsing Async in your Mobile Apps - Marek Safar
Using Async in your Mobile Apps - Marek Safar
 
Multithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IOMultithreading, Blocking IO and Async IO
Multithreading, Blocking IO and Async IO
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
Servlet 3.1 Async I/O
Servlet 3.1 Async I/OServlet 3.1 Async I/O
Servlet 3.1 Async I/O
 
Sync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-ioSync async-blocking-nonblocking-io
Sync async-blocking-nonblocking-io
 
Angular 2 어디까지 왔을까
Angular 2 어디까지 왔을까Angular 2 어디까지 왔을까
Angular 2 어디까지 왔을까
 
Think Async in Java 8
Think Async in Java 8Think Async in Java 8
Think Async in Java 8
 
Syncing Async
Syncing AsyncSyncing Async
Syncing Async
 
A Research Study into DevOps Bottlenecks
A Research Study into DevOps BottlenecksA Research Study into DevOps Bottlenecks
A Research Study into DevOps Bottlenecks
 

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

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Richard Lee
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 

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

Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Exploring Node.jS
Exploring Node.jSExploring Node.jS
Exploring Node.jS
 
Presentation on Japanese doc sprint
Presentation on Japanese doc sprintPresentation on Japanese doc sprint
Presentation on Japanese doc sprint
 
Node.js: CAMTA Presentation
Node.js: CAMTA PresentationNode.js: CAMTA Presentation
Node.js: CAMTA Presentation
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Plugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGemsPlugin-based software design with Ruby and RubyGems
Plugin-based software design with Ruby and RubyGems
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Clug 2011 March web server optimisation
Clug 2011 March  web server optimisationClug 2011 March  web server optimisation
Clug 2011 March web server optimisation
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Play Framework
Play FrameworkPlay Framework
Play Framework
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Play framework productivity formula
Play framework   productivity formula Play framework   productivity formula
Play framework productivity formula
 

Plus de Baruch Sadogursky

Plus de Baruch Sadogursky (20)

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

Dernier

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Dernier (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 

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
  • 10.
  • 11.
  • 12. Requirements – parallel file Downloads – Parallel file parts – interrupt/pause/resume – Progress events – Checksums caching
  • 13. First Association for “concurrent downloader”
  • 14.
  • 15. Lucky day: Download manager written in java!
  • 16.
  • 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
  • 18.
  • 19.
  • 20. Java.net.urlconnection 1. Memory wasteful (buffering) 2. Minimal API 3. Blocking streams
  • 21.
  • 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
  • 33.
  • 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
  • 36.
  • 37. Nio libraries – Most of them are servers –Netty, grizzly, etc – Apache Mina – Apache HTTP components asyncclient – Ning http client
  • 38.
  • 40.
  • 41.
  • 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(); }
  • 44.
  • 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(); }
  • 47.
  • 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
  • 54.
  • 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?
  • 59.
  • 60.
  • 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?
  • 65.
  • 66.
  • 67.
  • 68.
  • 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.”
  • 74.
  • 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)
  • 80.
  • 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
  • 84.
  • 85.
  • 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

Notes de l'éditeur

  1. Things that are not simple
  2. Why you dont’s
  3. Just avoid
  4. CURRENT – JB NEXT - YOAV
  5. Events are multiplexed by a single thread dispatcher
  6. TODO send table to back!!!
  7. Hypertext Transfer Protocol -- HTTP/1.1
  8. RFC2616 8.1.4
  9. Browsers go like:
  10. RAC is not concurrent!
  11. 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