180
Season of mists and mellow fruitfulness,

Back to Best

Embed Size (px)

DESCRIPTION

gok

Citation preview

Page 1: Back to Best

Season of mists and mellow fruitfulness,

Page 2: Back to Best
Page 3: Back to Best

Close bosom-friend of the maturing sun;

Page 4: Back to Best

Conspiring with him how to load and bless

Page 5: Back to Best

With fruit the vines that round the thatch-eves run;

Page 6: Back to Best
Page 7: Back to Best

To bend with apples the moss'd cottage-trees,

Page 8: Back to Best

And fill all fruit with ripeness to the core;

Page 9: Back to Best

To swell the gourd, and plump the hazel shells

Page 10: Back to Best

With a sweet kernel; to set budding more,

Page 11: Back to Best

And still more, later flowers for the bees,

Page 12: Back to Best

Until they think warm days will never cease,

Page 13: Back to Best

For Summer has o'er-brimm'd their clammy cells.

Page 14: Back to Best

Who hath not seen thee oft amid thy store?

Page 15: Back to Best

Sometimes whoever seeks abroad may find

Page 16: Back to Best

Thee sitting careless on a granary floor,

Page 17: Back to Best

Thy hair soft-lifted by the winnowing wind

Page 18: Back to Best

Or on a half-reap’d furrow sound asleep,

Page 19: Back to Best

Drowsed with the fume of poppies, while thy hook

Page 20: Back to Best

Spares the next swath and all its twinèd flowers:

Page 21: Back to Best

And sometimes like a gleaner thou dost keep

Page 22: Back to Best

Steady thy laden head across a brook;

Page 23: Back to Best

Or by a cyder-press, with patient look,

Page 24: Back to Best

Thou watchest the last oozings, hours by hours.

Page 25: Back to Best

Where are the songs of Spring? Ay, where are they?

Page 26: Back to Best

Think not of them, thou hast thy music too,—

Page 27: Back to Best

While barrèd clouds bloom the soft-dying day

Page 28: Back to Best

And touch the stubble-plains with rosy hue;

Page 29: Back to Best

Then in a wailful choir the small gnats mourn

Page 30: Back to Best

Among the river-sallows, borne aloft

Page 31: Back to Best

Or sinking as the light wind lives or dies;

sinking

Page 32: Back to Best

And full-grown lambs loud bleat from hilly bourn;

Page 33: Back to Best

Hedge-crickets sing; and now with treble soft

Page 34: Back to Best

The redbreast whistles from a garden-croft;

Page 35: Back to Best

And gathering swallows twitter in the skies.

Page 36: Back to Best
Page 37: Back to Best

Everything You Wanted to Know

About Writing Async, Concurrent HTTP Apps

in Java

Page 38: Back to Best

Agenda

Mostly this:

Page 39: Back to Best

Agenda

And this:

Page 40: Back to Best

Agenda

And this:

Page 41: Back to Best

About your [email protected]/jbaruch

linkd.in/jbaruch

stackoverflow.com/users/402053/jbaruch

Page 42: Back to Best

What Frog?

Page 43: Back to Best

What Frog?

Page 44: Back to Best

What Frog?

Page 45: Back to Best

What Frog?

Page 46: Back to Best
Page 47: Back to Best
Page 48: Back to Best

Requirements– parallel file Downloads– Parallel file parts– interrupt/pause/resume– Progress events– Checksums caching

Page 49: Back to Best

First Association for “concurrent downloader”

Page 50: Back to Best
Page 51: Back to Best

Lucky day: Download manager written in java!

Page 52: Back to Best
Page 53: Back to Best

Let’s look if we can use it!

1.No traceable license2.No website or docs3.No traceable sources4. It’s an app, not a lib

Page 54: Back to Best
Page 55: Back to Best
Page 56: Back to Best

Java.net.urlconnection1. Memory wasteful (buffering)2. Minimal API3. Blocking streams

Page 57: Back to Best
Page 58: Back to Best

What we’re looking for1. Async/non-blocking2. Event callbacks

Page 59: Back to Best

What is IT going to take1. Reactor2. nio

Page 60: Back to Best

Welcome to the reactor

Page 61: Back to Best

– pattern for lightweight concurrency

– Event driven– Threads reuse– Uses non-blocking Io

Page 62: Back to Best

Original pattern

http://www.dre.vanderbilt.edu/~schmidt/PDF/reactor-siemens.pdf

Page 63: Back to Best

Guess the author by the diagram

http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf

Page 64: Back to Best

In Java, Reactor

means NIO

Page 65: Back to Best

Selector as a multiplexer

Page 66: Back to Best

Java version - RegisteringSocketChannel 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);

Page 67: Back to Best

Java version - Dispatcherwhile (!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();

}

Page 68: Back to Best

Handling reactor events is complex

–Need to maintain state–Buffering – assembling chunks

–Coordinating async events

Page 69: Back to Best
Page 70: Back to Best

Nio libraries–Most of them are servers

–Netty, grizzly, etc.–Apache Mina–Apache HTTP components asyncclient

–Ning http client

Page 71: Back to Best

–Client and server nio library–Evolved from netty–Latest release October 2012

Page 72: Back to Best
Page 73: Back to Best

Nio libraries

Page 74: Back to Best
Page 75: Back to Best

Ning’s async http client

Page 76: Back to Best
Page 77: Back to Best
Page 78: Back to Best

Here it is!

Page 79: Back to Best

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();}

Page 80: Back to Best
Page 81: Back to Best

HAC Concepts–Request producer–Response consumer

Page 82: Back to Best
Page 83: Back to Best
Page 84: Back to Best

Choosing between ning and http asyncclient

Page 85: Back to Best

"All problems in computer science can be solved by another level of indirection"

David Wheeler

Page 86: Back to Best

public interface HttpProviderDownloadHandler {

void onResponseReceived(int statusCode, Map<String, List<String>> headers);

boolean onBytesReceived(ByteBuffer buf);

void onFailed(Throwable error);

void onCanceled();

void onCompleted();}

Page 87: Back to Best

Head to head

Feature/Library Ning client Http Async ClientMaturity Good Very new (early 2014)Download cancelation

Easy With bugs

Progress hooks

Events not granular enough

Just use onByteReceived()

Documentation A bit sparse MinimalServer-side counterpart

None, client only

org.apache.httpcomponentshttpcore-nio

Page 88: Back to Best

Performance?

http://blogs.atlassian.com/2013/07/http-client-performance-io/

Page 89: Back to Best

Rfc2616: a universe of its own

Page 90: Back to Best
Page 91: Back to Best

Confused?

Page 92: Back to Best

Just read some stackoverflow(and improve your rep as you go)

Page 93: Back to Best

And that one for

discovering that range

header is lost on redirect

Page 94: Back to Best

Question!

What should be content-length when using compression?

Page 95: Back to Best
Page 96: Back to Best
Page 97: Back to Best

https://github.com/http2/http2-spec/issues/46

Page 98: Back to Best

Question!

Why when redirected to CDN all the chunks start from zero?

Page 99: Back to Best

HttpAsyncClientBuilder builder = HttpAsyncClients.custom();// add redirect strategy that copies "range" headers, if existbuilder.setRedirectStrategy(new DefaultRedirectStrategy() {

@Overridepublic HttpUriRequest getRedirect(HttpRequest request, HttpResponse

response, HttpContext context)HttpUriRequest redirectRequest = super.getRedirect(request,

response, context);// copy "Range" headers, if existHeader[] rangeHeaders = request.getHeaders(HttpHeaders.RANGE);

if (rangeHeaders != null) {for (Header header : rangeHeaders) {

redirectRequest.addHeader(header);}

}return redirectRequest;

}});

Page 100: Back to Best

Question!

How many simultaneous connections should I open?

Page 101: Back to Best
Page 102: Back to Best
Page 103: Back to Best
Page 104: Back to Best
Page 105: Back to Best

Question!

What’s wrong with the following code?

Page 106: Back to Best

public static String encodeUrl(String urlStr) { URLEncoder.encode(urlStr, "UTF-8"); ...}

Page 107: Back to Best

Decoded URLs cannot bere-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

Page 108: Back to Best

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.”

Page 109: Back to Best

AHC Alternatives

Page 110: Back to Best
Page 111: Back to Best

Question!

How do I close a socket correctly?

Page 112: Back to Best

How hard can it be to close a socket?

Page 113: Back to Best

The art of socket closing

http://www.safaribooksonline.com/library/view/http-the-definitive/1565925092/ch04s07.html

Page 114: Back to Best

Half-closed: no new customers

Page 115: Back to Best

Never block in socket close()

The other side expects you to clean up nicely

It will give up on time outYou will wait (forever)

Page 116: Back to Best
Page 117: Back to Best

Remember?

Page 118: Back to Best

Question!

How can I write file parts concurrently?

Page 119: Back to Best

– Write to separate files, combine on finish

– Write to same file, seeking to the right position

Page 120: Back to Best
Page 121: Back to Best
Page 122: Back to Best

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?!

Page 123: Back to Best

VM Level File Locking

Page 124: Back to Best

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

Page 125: Back to Best

VM Level File LockingReentrantReadWriteLock.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"); } ...}

Page 126: Back to Best

What’s next?

Page 127: Back to Best

http/2– Mostly standardizing Google's

spdy– Header compression– multiplexing– Prioritization– Server push – On the way clear some stuff– E.g. compressed content length

Page 128: Back to Best

Ease the load

Page 130: Back to Best

No, Thank you!

Page 131: Back to Best

A Quick Tourof Logos

The Logical Appeal

Page 132: Back to Best

So what exactly is logic? Who cares?Informally, logic is about saying things that make sense. You can think of it in that way if you like.

“It's pretty sunny today, so you should wear sunscreen.”

Formally, logic is the art of arguing – not like a fight or debate, but by using the information we already

know to draw new and useful conclusions.

“If it's sunny today, you should wear sunscreen.Indeed it is sunny today.

Therefore, you should wear sunscreen.”

Page 133: Back to Best

“But wait. That just looked like the exact same thing you said before, you hack.”

Well, yes. But that's how an argument looks in standardform! You can break down any argument into this form;that makes it easier to think about.

If it's sunny today, you should wear sunscreen.

It is sunny today.___________________________________________

Therefore, you should wear sunscreen.

Premises/givens

Conclusion(Premises always come first, and the conclusion always comes last.)

Page 134: Back to Best

How about a more complex argument?

1. This piece of fresh fruit is fuzzy.2. It also has seeds.

3. If a fruit is fuzzy, it's either a kiwi or a peach.4. Peaches have a pit; they don't have seeds.

5. So the fruit can't be a peach.6. So the fruit must be a kiwi.

Which of the above sentences is a conclusion?

Page 135: Back to Best

How about a more complex argument?

1. This piece of fresh fruit is fuzzy.2. It also has seeds.

3. If a fruit is fuzzy, it's either a kiwi or a peach.4. Peaches have a pit; they don't have seeds.

5. So the fruit can't be a peach.6. So the fruit must be a kiwi.

Good logic lets us cobble together lots ofdifferent pieces of information, and tell from

them what's probably or definitely true.

Page 136: Back to Best

But what counts as “good logic”?

That argument was good (made sense), because the conclusion followed from the premises. We'll see what this means in a moment.

Why don't we look at a bad argument?

Page 137: Back to Best

But what counts as “good logic”?

Some people have fallen off cliffs and lived.

Therefore, if I jump off this cliff, I will definitely be fine.

“Come on.What couldpossibly gowrong?”

Page 138: Back to Best

But what counts as “good logic”?

Some people have fallen off cliffs and lived.

Therefore, if I jump off this cliff, I will definitely be fine.

This argument is weak. Although the premise is true,it's easy to think of ways (very painful ways) that theconclusion could be false. The easiest way to spot badlogic is to do just that: try to think of another way out.

(Philosophers call these counterexamples).

Page 139: Back to Best

But what counts as “good logic”?

Let's look at two kinds of arguments.1. Deductive reasoning: All interns can breathe fire. So Philip

can breathe fire.

Is there a piece of the puzzle missing?

Page 140: Back to Best

But what counts as “good logic”?

Let's look at two kinds of arguments.1. Deductive reasoning: All interns can breathe fire. Philip is an

intern. So Philip can breathe fire.

Sometimes you may encounter “hidden” statementsand ideas, which the writer sneaks in but doesn'tsay outright.

Page 141: Back to Best

But what counts as “good logic”?

Let's look at two kinds of arguments.1. Deductive reasoning:

All interns can breathe fire. Philip is an intern. So Philip can breathe fire.

Are the premises true?If so, then the conclusion's100% guaranteed true.No getting around it!

Page 142: Back to Best

But what counts as “good logic”?

Let's look at two kinds of arguments.2. Inductive reasoning:

I touched a stove and it burned me. I did this fifty times, and the same thing happened. So

the next time I touch the stove, it will burn me.

Are the premises true?If so, then the conclusion'sprobably true. There mightstill be exceptions.

LIKE WHAT?

Page 143: Back to Best

How is this useful to me?

Like Mr. Morgan said, the ability to make strong logical arguments will become more and more important later on in high school and college.

Pathos and ethos are still valuable! But your audience will be a lot better at questioning them. Logos is handy because, if you use it well, it can't really be disproved.

Page 144: Back to Best

How is this useful to me?But even better is the superpower to spot weak logic.

Next time you watch TV or go online (with your parents' permission, of course), try to keep track of how many different arguments are being pitched to you by ads. How much info is given to you? How much is left out?

Page 145: Back to Best

What time is it?Adven- wait, no. Activity time!

Pair off into groups of four. Each group will receive an exampleof a poor argument (these may be either inductive or deductive).

With your group, you will have 5 minutes to try to come up withone counterexample - one way in which the argumentcould be wrong, even if the premises are definitely true.Poke it full of holes!Also, choose a group representative to tell us your reasoning.

(It's OK to imagine unlikely or weird explanations;don't be afraid to think outside the box.Oddly enough, logic has very little to do with facts.)

Page 146: Back to Best

Some examples:ARGUMENT: “I pulled an all-nighter studying for last week's bigtest, and I ended up with an A. Tiredness must make me smart!”

COUNTER: What if you got an A because you actually studied?Or maybe the test was going to be easy for you all along?

ARGUMENT: “If I play with Dad's power tools, he'll yell at me.But Dad is yelling at me for something. So I guess I must haveplayed with the power tools.”

COUNTER: What if he's yelling at you for a different reason:scratching the car, or hammer-throwing the cat onto the roof?

Page 147: Back to Best

Season of mists and mellow fruitfulness,

Page 148: Back to Best

Close bosom-friend of the maturing sun;

Page 149: Back to Best

Conspiring with him how to load and bless

Page 150: Back to Best

With fruit the vines that round the thatch-eves run;

Page 151: Back to Best

To bend with apples the moss'd cottage-trees,

Page 152: Back to Best

And fill all fruit with ripeness to the core;

Page 153: Back to Best

To swell the gourd, and plump the hazel shells

Page 154: Back to Best

With a sweet kernel; to set budding more,

Page 155: Back to Best

And still more, later flowers for the bees,

Page 156: Back to Best

Until they think warm days will never cease,

Page 157: Back to Best

For Summer has o'er-brimm'd their clammy cells.

Page 158: Back to Best

Who hath not seen thee oft amid thy store?

Page 159: Back to Best

Sometimes whoever seeks abroad may find

Page 160: Back to Best

Thee sitting careless on a granary floor,

Page 161: Back to Best

Thy hair soft-lifted by the winnowing wind

Page 162: Back to Best

Or on a half-reap’d furrow sound asleep,

Page 163: Back to Best

Drowsed with the fume of poppies, while thy hook

Page 164: Back to Best

Spares the next swath and all its twinèd flowers:

Page 165: Back to Best

And sometimes like a gleaner thou dost keep

Page 166: Back to Best

Steady thy laden head across a brook;

Page 167: Back to Best

Or by a cyder-press, with patient look,

Page 168: Back to Best

Thou watchest the last oozings, hours by hours.

Page 169: Back to Best

Where are the songs of Spring? Ay, where are they?

Page 170: Back to Best

Think not of them, thou hast thy music too,—

Page 171: Back to Best

While barrèd clouds bloom the soft-dying day

Page 172: Back to Best

And touch the stubble-plains with rosy hue;

Page 173: Back to Best

Then in a wailful choir the small gnats mourn

Page 174: Back to Best

Among the river-sallows, borne aloft

Page 175: Back to Best

Or sinking as the light wind lives or dies;

sinking

Page 176: Back to Best

And full-grown lambs loud bleat from hilly bourn;

Page 177: Back to Best

Hedge-crickets sing; and now with treble soft

Page 178: Back to Best

The redbreast whistles from a garden-croft;

Page 179: Back to Best

And gathering swallows twitter in the skies.

Page 180: Back to Best