[Login]

Java Snippets

Create a thread

new Thread(() -> {
   System.out.println("Hello world");
}).start();

Concurrent Set

private final Set<String> mySet = Collections.newSetFromMap(Maps.<String, Boolean>newConcurrentMap());

Retries

/*-
<dependency>
  <groupId>net.jodah</groupId>
  <artifactId>failsafe</artifactId>
  <version>1.1.0</version>
</dependency>
*/
final RetryPolicy policy = new RetryPolicy()
    .retryOn(Exception.class)
    .withDelay(1, TimeUnit.SECONDS)
    .withMaxRetries(3);
     
Failsafe.with(RETRY_POLICY)
    .onSuccess(cxn -> log.debug("something {}", key))
    .onFailure(failure -> log.error("Failed {}", key, failure))
    .run(() -> {
       System.out.println("doing something that might throw");
    });

Execute tasks in parallel and join

ExecutorService executor = Executors.newFixedThreadPool(1024);
 
List<String> values = new ArrayList<>();
 
final List<Callable<String>> tasks = values.stream().map(value -> {
    return (Callable<String>) () -> {
        return computeSomethingWith(value);
    };
}).collect(Collectors.toList());
 
// Wait for completion
final List<Future<String>> futures = executor.invokeAll(tasks, 30, TimeUnit.SECONDS);
 
// Get results
final List<String> results = futures.stream()
        .map(future -> {
            try {
                return future.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        })
        .collect(Collectors.toList());

Async cache

/**
 * @param ticker
 *            A ticker
 * @param unit
 *            Unit for ttl/e
 * @param ttl
 *            The cache will update asynchronously in the background after this time
 * @param tte
 *            The cache will stop returning stale values after this time
 * @param maxSize
 *            The max size of the cache
 */
private LoadingCache<Key, CacheValue> buildCache(Ticker ticker, TimeUnit unit, int ttl, int tte, int maxSize) {
    final ExecutorService executor = Executors.newCachedThreadPool();
    final CacheLoader<Key, CacheValue> loader = new CacheLoader<Key, CacheValue>() {
        @Override
        public CacheValue load(Key key) {
            return loadExpensiveThing(key);
        }
    };
    return CacheBuilder.newBuilder()
            .maximumSize(maxSize)
            .ticker(ticker)
            .refreshAfterWrite(ttl, unit)
            .expireAfterWrite(tte, unit)
            .build(CacheLoader.asyncReloading(loader, executor));
}

Lombok

// Builder
@Builder(builderClassName = "Builder", toBuilder = true)
  
// Constructor
@RequiredArgsConstructor(access = AccessLevel.PRIVATE, onConstructor = @__({ @Inject }))
  
// Logging
@Slf4j

// Builder with Jackson
@Value
@JsonDeserialize(builder = Person.Builder.class)
@lombok.Builder(builderClassName = "Builder")
public static final class Person {
    private final String name;
    private final String email;

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonPOJOBuilder(withPrefix = "")
    public static class Builder {
        // Required for Jackson
    }
}

Create an immutable pojo

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;

@JsonDeserialize(builder = StartBuildRequest.Builder.class)
@Value
@Builder(builderClassName = "Builder")
public class PersonRequest {
    private final String firstName;
    private final String lastName;
    private final int age;

    @JsonPOJOBuilder(withPrefix = "")
    public static final class Builder {
        // Nothing goes here, but it needs to exist
    }
}

Running and executing

java -jar target/something-0.0.0.jar