Skip to content

Instantly share code, notes, and snippets.

View gaul's full-sized avatar

Andrew Gaul gaul

View GitHub Profile
@gaul
gaul / SetFixedLengthStreamingMode.java
Last active December 22, 2015 07:39
Demonstrate how to call setFixedLengthStreamingMode with an int argument in Java 6 and with a long argument in Java 7.
/**
* Demonstrate how to call setFixedLengthStreamingMode with an int argument in
* Java 6 and with a long argument in Java 7.
*/
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
public class SetFixedLengthStreamingMode {
@gaul
gaul / CaseInsensitiveMap.java
Created July 30, 2013 02:46
Demonstrate a case-insensitive map using Treemap and a comparator.
import java.util.TreeMap;
public class CaseInsensitiveMap {
public static void main(String[] args) {
TreeMap<String, String> map = new TreeMap<String, String>(
String.CASE_INSENSITIVE_ORDER);
assert map.isEmpty();
map.put("a", "b");
assert map.size() == 1;
@gaul
gaul / gist:5863490
Created June 25, 2013 23:41
Exception catch order
/**
* Demonstrate that exception catch order is relevant and javac warns when
* catching a more specific exception after a less specific one:
*
* CatchOrder.java:20: exception java.io.FileNotFoundException has already been caught
* } catch (FileNotFoundException fnfe) {
* ^
* 1 error
*/
@gaul
gaul / gist:5807246
Created June 18, 2013 17:02
Demonstrate implicit StringBuilder
$ cat foo.java
public class foo {
private foo() {}
public static String method(int x, Long y) {
return "x: " + x + " y: " + y.longValue();
}
}
$ javac foo.java
@gaul
gaul / gist:5486495
Last active December 16, 2015 19:39
double checked locking alternative
enum { uninitialized, initializing, initialized };
static state = uninitialized;
static var = 0;
while (true) {
switch(cmpxchg(state, initializing, uninitialized)) {
case uninitialized:
var = stmt;
xchg(state, initialized);
return;
case initializing:
@gaul
gaul / gist:5470942
Created April 26, 2013 22:45
Atomic loads on x86
$ cat -n atomic.cc
1 #include <atomic>
2
3 int func(std::atomic<int> *x)
4 {
5 return std::atomic_load(x);
6 }
$ g++ -O2 -std=c++0x -S -o - atomic.cc
.file "atomic.cc"
@gaul
gaul / gist:5306774
Created April 4, 2013 00:45
Demonstrate Valgrind --track-origins
$ cat foo.c
#include <stdio.h>
#include <stdlib.h>
char *func1(void) { return malloc(256); }
char *func2(void) { return func1(); }
int main(int argc, char *argv[])
{
char *ptr = func2();