Skip to content

Commit

Permalink
Add fb-contrib static analysis rules
Browse files Browse the repository at this point in the history
  • Loading branch information
ben-manes committed Jan 10, 2022
1 parent b326952 commit 5e834f8
Show file tree
Hide file tree
Showing 40 changed files with 232 additions and 171 deletions.
27 changes: 12 additions & 15 deletions caffeine/build.gradle
Expand Up @@ -82,7 +82,7 @@ tasks.named('compileCodeGenJava').configure {
}

tasks.named('jar').configure {
dependsOn(compileCodeGenJava)
dependsOn compileCodeGenJava
manifest {
attributes 'Bundle-SymbolicName': 'com.github.ben-manes.caffeine'
attributes 'Import-Package': ''
Expand All @@ -104,34 +104,31 @@ sonarqube {
def generateLocalCaches = tasks.register('generateLocalCaches', JavaExec) {
mainClass = 'com.github.benmanes.caffeine.cache.LocalCacheFactoryGenerator'
classpath = sourceSets.javaPoet.runtimeClasspath
args "${buildDir}/generated-sources/"

outputs.upToDateWhen { !tasks.compileJavaPoetJava.didWork }
outputs.dir "${buildDir}/generated-sources/"
outputs.cacheIf { true }
args "${buildDir}/generated-sources/"
dependsOn compileJavaPoetJava
}

def generateNodes = tasks.register('generateNodes', JavaExec) {
mainClass = 'com.github.benmanes.caffeine.cache.NodeFactoryGenerator'
classpath = sourceSets.javaPoet.runtimeClasspath
args "${buildDir}/generated-sources/"

outputs.upToDateWhen { !tasks.compileJavaPoetJava.didWork }
outputs.dir "${buildDir}/generated-sources/"
outputs.cacheIf { true }
args "${buildDir}/generated-sources/"
dependsOn compileJavaPoetJava
}

tasks.named('compileJava').configure {
finalizedBy(compileCodeGenJava)
dependsOn(generateLocalCaches)
dependsOn(generateNodes)
dependsOn generateLocalCaches, generateNodes
finalizedBy compileCodeGenJava
}
tasks.named('compileJavaPoetJava').configure {
finalizedBy generateLocalCaches, generateNodes
}
['compileTestJava', 'pmdMain', 'spotbugsMain'].collect { tasks.named(it) }*.configure {
dependsOn(compileCodeGenJava)
dependsOn compileCodeGenJava
}
tasks.named('sourcesJar').configure {
dependsOn(generateLocalCaches)
dependsOn(generateNodes)
dependsOn generateLocalCaches, generateNodes
}

tasks.register('memoryOverhead', JavaExec) {
Expand Down
Expand Up @@ -50,22 +50,14 @@ public enum Feature {
Feature.EXPIRE_ACCESS, Feature.WEAK_KEYS, Feature.INFIRM_VALUES,
Feature.WEAK_VALUES, Feature.SOFT_VALUES);

public static String makeEnumName(Iterable<Feature> features) {
return Streams.stream(features)
.map(Feature::name)
.collect(Collectors.joining("_"));
}

public static String makeEnumName(String enumName) {
return CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, enumName);
}

public static String makeClassName(Iterable<Feature> features) {
String enumName = makeEnumName(features);
return makeClassName(enumName);
}

public static String makeClassName(String enumName) {
String enumName = Streams.stream(features)
.map(Feature::name)
.collect(Collectors.joining("_"));
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, enumName);
}

Expand Down
Expand Up @@ -110,12 +110,12 @@ public final class LocalCacheFactoryGenerator {
private final List<TypeSpec> factoryTypes;

@SuppressWarnings("NullAway.Init")
public LocalCacheFactoryGenerator(Path directory) {
LocalCacheFactoryGenerator(Path directory) {
this.directory = requireNonNull(directory);
this.factoryTypes = new ArrayList<>();
}

void generate() throws IOException {
void generate() throws FormatterException, IOException {
factory = TypeSpec.classBuilder("LocalCacheFactory")
.addModifiers(Modifier.FINAL)
.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build());
Expand Down Expand Up @@ -159,7 +159,7 @@ private void writeJavaFile() throws IOException {
}
}

private void reformat() throws IOException {
private void reformat() throws FormatterException, IOException {
try (Stream<Path> stream = Files.walk(directory)) {
List<Path> files = stream
.filter(path -> path.toString().endsWith(".java"))
Expand All @@ -170,8 +170,6 @@ private void reformat() throws IOException {
String formatted = formatter.formatSourceAndFixImports(source);
Files.writeString(file, formatted);
}
} catch (FormatterException e) {
throw new RuntimeException(e);
}
}

Expand Down Expand Up @@ -285,7 +283,7 @@ private static String encode(String className) {
.replaceFirst("_REFRESH_WRITE", "R");
}

public static void main(String[] args) throws IOException {
public static void main(String[] args) throws FormatterException, IOException {
new LocalCacheFactoryGenerator(Paths.get(args[0])).generate();
}
}
Expand Up @@ -126,12 +126,12 @@ public final class NodeFactoryGenerator {
private final List<TypeSpec> nodeTypes;

@SuppressWarnings("NullAway.Init")
public NodeFactoryGenerator(Path directory) {
NodeFactoryGenerator(Path directory) {
this.directory = requireNonNull(directory);
this.nodeTypes = new ArrayList<>();
}

void generate() throws IOException {
void generate() throws FormatterException, IOException {
nodeFactory = TypeSpec.interfaceBuilder("NodeFactory")
.addTypeVariable(kTypeVar)
.addTypeVariable(vTypeVar);
Expand Down Expand Up @@ -161,7 +161,7 @@ private void writeJavaFile() throws IOException {
}
}

private void reformat() throws IOException {
private void reformat() throws FormatterException, IOException {
try (Stream<Path> stream = Files.walk(directory)) {
List<Path> files = stream
.filter(path -> path.toString().endsWith(".java"))
Expand All @@ -172,8 +172,6 @@ private void reformat() throws IOException {
String formatted = formatter.formatSourceAndFixImports(source);
Files.writeString(file, formatted);
}
} catch (FormatterException e) {
throw new RuntimeException(e);
}
}

Expand Down Expand Up @@ -368,7 +366,7 @@ private static String encode(String className) {
.replaceFirst("_SIZE", "S");
}

public static void main(String[] args) throws IOException {
public static void main(String[] args) throws FormatterException, IOException {
new NodeFactoryGenerator(Paths.get(args[0])).generate();
}
}
Expand Up @@ -50,7 +50,7 @@ protected void execute() {
addStaticBlock();
}

public void addStaticBlock() {
private void addStaticBlock() {
if (context.varHandles.isEmpty()) {
return;
}
Expand Down
Expand Up @@ -32,34 +32,29 @@ public class FactoryBenchmark {
private final ReflectionFactory reflectionFactory = new ReflectionFactory();
private final MethodHandleFactory methodHandleFactory = new MethodHandleFactory();

@State(Scope.Thread)
public static class ThreadState {
int i;
}

@Benchmark
public Alpha direct(ThreadState state) {
return new Alpha(state.i++);
public Alpha direct() {
return new Alpha();
}

@Benchmark
public Alpha methodHandle_invoke(ThreadState state) {
return methodHandleFactory.invoke(state.i++);
public Alpha methodHandle_invoke() {
return methodHandleFactory.invoke();
}

@Benchmark
public Alpha methodHandle_invokeExact(ThreadState state) {
return methodHandleFactory.invokeExact(state.i++);
public Alpha methodHandle_invokeExact() {
return methodHandleFactory.invokeExact();
}

@Benchmark
public Alpha reflection(ThreadState state) {
return reflectionFactory.newInstance(state.i++);
public Alpha reflection() {
return reflectionFactory.newInstance();
}

static final class MethodHandleFactory {
private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
private static final MethodType METHOD_TYPE = MethodType.methodType(void.class, int.class);
private static final MethodType METHOD_TYPE = MethodType.methodType(void.class);

private final MethodHandle methodHandle;

Expand All @@ -71,17 +66,17 @@ static final class MethodHandleFactory {
}
}

Alpha invoke(int x) {
Alpha invoke() {
try {
return (Alpha) methodHandle.invoke(x);
return (Alpha) methodHandle.invoke();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}

Alpha invokeExact(int x) {
Alpha invokeExact() {
try {
return (Alpha) methodHandle.invokeExact(x);
return (Alpha) methodHandle.invokeExact();
} catch (Throwable e) {
throw new RuntimeException(e);
}
Expand All @@ -93,27 +88,22 @@ static final class ReflectionFactory {

ReflectionFactory() {
try {
constructor = Alpha.class.getConstructor(int.class);
constructor = Alpha.class.getConstructor();
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
}
}

Alpha newInstance(int x) {
Alpha newInstance() {
try {
return constructor.newInstance(x);
return constructor.newInstance();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}

static final class Alpha {
@SuppressWarnings("unused")
private final int x;

public Alpha(int x) {
this.x = x;
}
public Alpha() {}
}
}
Expand Up @@ -62,7 +62,7 @@ public void setupThreadLocal() {
threadLocal = ThreadLocal.withInitial(() -> {
for (int i = 0; i < ARENA_SIZE; i++) {
// Populates the internal hashmap to emulate other thread local usages
ThreadLocal.withInitial(Thread.currentThread()::getId);
ThreadLocal.withInitial(Thread.currentThread()::getId).get();
}
return selectSlot(ThreadLocalRandom.current().nextInt());
});
Expand Down
Expand Up @@ -375,7 +375,7 @@ public void notifyRemoval(@Nullable K key, @Nullable V value, RemovalCause cause

/* --------------- Eviction Listener Support --------------- */

public void notifyEviction(@Nullable K key, @Nullable V value, RemovalCause cause) {
private void notifyEviction(@Nullable K key, @Nullable V value, RemovalCause cause) {
if (evictionListener == null) {
return;
}
Expand Down
Expand Up @@ -37,6 +37,7 @@
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
Expand Down Expand Up @@ -287,8 +288,9 @@ private void addNewEntries(Map<? extends K, ? extends V> result) {
static final class NullMapCompletionException extends CompletionException {
private static final long serialVersionUID = 1L;

public NullMapCompletionException() {
super("null map", null);
@SuppressWarnings("UnsynchronizedOverridesSynchronized")
@Override public Throwable fillInStackTrace() {
return this;
}
}
}
Expand Down Expand Up @@ -526,12 +528,12 @@ public Map<K, V> getAll(Iterable<? extends K> keys,
}

@SuppressWarnings({"PMD.AvoidThrowingNullPointerException", "PMD.PreserveStackTrace"})
protected static <T> T resolve(CompletableFuture<T> future) {
protected static <T> T resolve(Future<T> future) {
try {
return future.get();
} catch (ExecutionException e) {
if (e.getCause() instanceof NullMapCompletionException) {
throw new NullPointerException(e.getCause().getMessage());
throw new NullPointerException("null map");
} else if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException) e.getCause();
} else if (e.getCause() instanceof Error) {
Expand Down
Expand Up @@ -21,12 +21,10 @@
import java.lang.System.Logger;
import java.lang.System.Logger.Level;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
* A scheduler that submits a task to an executor after a given delay.
Expand Down Expand Up @@ -99,8 +97,8 @@ public Future<?> schedule(Executor executor, Runnable command, long delay, TimeU
}

final class ExecutorServiceScheduler implements Scheduler, Serializable {
static final Logger logger = System.getLogger(ExecutorServiceScheduler.class.getName());
static final long serialVersionUID = 1;
private static final Logger logger = System.getLogger(ExecutorServiceScheduler.class.getName());
private static final long serialVersionUID = 1;

final ScheduledExecutorService scheduledExecutorService;

Expand Down Expand Up @@ -129,8 +127,8 @@ public Future<?> schedule(Executor executor, Runnable command, long delay, TimeU
}

final class GuardedScheduler implements Scheduler, Serializable {
static final Logger logger = System.getLogger(GuardedScheduler.class.getName());
static final long serialVersionUID = 1;
private static final Logger logger = System.getLogger(GuardedScheduler.class.getName());
private static final long serialVersionUID = 1;

final Scheduler delegate;

Expand Down Expand Up @@ -175,12 +173,11 @@ enum DisabledFuture implements Future<Void> {
@Override public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override public Void get() throws InterruptedException, ExecutionException {
@Override public Void get(long timeout, TimeUnit unit) {
requireNonNull(unit);
return null;
}
@Override public Void get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
requireNonNull(unit);
@Override public Void get() {
return null;
}
}
Expand Up @@ -78,7 +78,8 @@ enum SingletonWeigher implements Weigher<Object, Object> {
}

final class BoundedWeigher<K, V> implements Weigher<K, V>, Serializable {
static final long serialVersionUID = 1;
private static final long serialVersionUID = 1;

final Weigher<? super K, ? super V> delegate;

BoundedWeigher(Weigher<? super K, ? super V> delegate) {
Expand Down
Expand Up @@ -26,7 +26,7 @@
* @author ben.manes@gmail.com (Ben Manes)
*/
final class WriteThroughEntry<K, V> extends SimpleEntry<K, V> {
static final long serialVersionUID = 1;
private static final long serialVersionUID = 1;

private final ConcurrentMap<K, V> map;

Expand Down

0 comments on commit 5e834f8

Please sign in to comment.