Skip to content

Instantly share code, notes, and snippets.

@bandrzejczak
Created January 8, 2015 21:14
Show Gist options
  • Save bandrzejczak/d33a175b6179425b5c91 to your computer and use it in GitHub Desktop.
Save bandrzejczak/d33a175b6179425b5c91 to your computer and use it in GitHub Desktop.
Volatile method in Java
import org.junit.Test;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class VolatileMethodsSpec {
@Test
public void shouldCreateVolatileMethod() {
//when
Method[] methods = Inner.class.getDeclaredMethods();
//then
assertThat(
Arrays
.stream(methods)
.filter(m -> m.getName().equals("add"))
.anyMatch(m -> Modifier.isVolatile(m.getModifiers()))
).isTrue();
}
private class Inner extends ArrayList<String>{
/*
This method creates two methods - one regular, for add(String)
and one volatile for add(Object), because you could assign Inner to List<?>,
and List would have add(Object) method. Generics, huh? Pretty fucked up, isn't it?
*/
@Override
public boolean add(String s) {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment