Last active
February 25, 2019 19:05
-
-
Save magro/04ae851a5f963f05c75380a8e7715dac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.net.URL; | |
import java.nio.channels.Channels; | |
import java.time.Instant; | |
import java.util.stream.Collectors; | |
public class Blocking { | |
public static void main(String[] args) throws Exception { | |
final Thread reader = new Thread() { | |
@Override | |
public void run() { | |
log("Reader running..."); | |
try { | |
String content = readBlockingIO(new URL("https://httpbin.org/delay/10")); | |
// String content = readNIO(new URL("https://httpbin.org/delay/5")); | |
log(content); | |
} catch(Exception e) { | |
log("Reading failed with " + e); | |
e.printStackTrace(); | |
} | |
} | |
}; | |
reader.start(); | |
log("Reader started, waiting..."); | |
Thread.sleep(2000); | |
new Thread() { | |
@Override | |
public void run() { | |
log("Interrupting reader..."); | |
reader.interrupt(); | |
} | |
}.start(); | |
reader.join(); | |
log("Done, exiting"); | |
} | |
private static String readBlockingIO(URL url) throws IOException { | |
InputStream in = url.openStream(); | |
log("Reading from input..."); | |
BufferedReader buffer = new BufferedReader(new InputStreamReader(in)); | |
return buffer.lines().collect(Collectors.joining("\n")); | |
} | |
private static String readNIO(URL url) throws IOException { | |
InputStream in = url.openStream(); | |
log("Reading from input..."); | |
BufferedReader buffer = new BufferedReader(Channels.newReader(Channels.newChannel(in), "UTF-8")); | |
return buffer.lines().collect(Collectors.joining("\n")); | |
} | |
private static void log(String msg) { | |
System.out.println("[" + Instant.now() + "] " + msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment