Skip to content

Instantly share code, notes, and snippets.

@danielshaya
danielshaya / NextTask.java
Created April 16, 2015 20:02
How to handle an interrupt correctly
public Task getNextTask(BlockingQueue<Task> queue){
boolean interrupted = false;
try{
while(true){
try{
return queue.take();
}catch(InterruptedException e){
interrupted = true;
//retry
}
package util;
public class LatencyMeasureExample {
public static void main(String[] args) throws InterruptedException{
//Below are a couple of examples
LatencyMeasure lm = new LatencyMeasure(1000000);
System.out.println("Thread.sleep() random");
for (int i = 0; i < 100000; i++) {
lm.startMeasure();
@danielshaya
danielshaya / LatencyMeasure.java
Last active August 29, 2015 14:20
LatencyMeasure
package util;
import java.util.Arrays;
public class LatencyMeasure {
private long[] times;
private long time;
private int index=0;
@danielshaya
danielshaya / Allocation.java
Last active August 29, 2015 14:20
Code in tight loops
package util;
import java.util.Set;
public class Allocation {
static int iterations = 10_000_000;
public static void main(String[] args) {
new Thread(){
package util;
public class Allocation1 {
static int iterations = 10_000_000;
public static void main(String[] args) {
for (int i = 0; i <3 ; i++) {
testNoAllocations();
testAllocations();
}
package util;
public class Allocation2 {
static int iterations = 10_000_000;
public static void main(String[] args) {
for (int i = 0; i <3 ; i++) {
testNoAllocations();
testAllocations();
package util;
import java.io.*;
import java.util.zip.GZIPOutputStream;
public class LambdaExceptions {
public static void main(String[] args) {
try {
//Write with compression
writeToFile(new File("test"), "Hello World", GZIPOutputStream::new);
private static void writeToFile(File file, String value,
Function<OutputStream, OutputStream> writing) throws IOException{
try (PrintWriter pw = new PrintWriter(new BufferedOutputStream
(writing.apply(new FileOutputStream(file))))) {
pw.write(value);
}
}
public static void main(String[] args) {
try {
//Write with compression
//DOES NOT COMPILE!!
writeToFile(new File("test"), "Hello World", GZIPOutputStream::new);
//Just use the FileOutputStream
writeToFile(new File("test"), "Hello World", i->i);
}catch(IOException e){
//deal with exception as you choose
}
public static void main(String[] args) {
try {
//Write with compression
//COMPILES BUT SO UGLY
writeToFile(new File("test"), "Hello World", i -> {
try {
return new GZIPOutputStream(i);
} catch (IOException e) {
//HOW ARE WE SUPPOSED TO DEAL WITH THIS EXCEPTION??
throw new AssertionError(e);