Category Archives: java

wait(), notify(), notifyAll(), sleep()

wait(), notify(). obj.wait() will release the object’s lock, until some other thread calls obj.notify(). When calling obj.wait(), current thread should own obj. Normally, it is called like: synchronized(obj) { // acquire obj obj.wait(); } IllegalMonitorStateException will be thrown if current thread doesn’t own obj. obj.notify() wakes up single thread which waits for obj lock. obj.notifyAll()… Read More »

Java Coding Style

Guava: Preconditions.checkNotNull Guava: Preconditions.checkArgument JDK: Objects.requireNotNon NullPointerException or IllegalArgumentException 1. Many APIs in the JDK pro-actively throws NullPointerException. This suggests that throwing NPE is a Java convention. 2. Effective Java Item 60: “Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds… Read More »

default keyword in Java

default can be used in switch statement. default can be used in annotation, specifying the default value. For example: @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface Todo { String author() default “Yash”; } @Todo(author = “Yashwant”) public void incompleteMethod1() { //Some business logic is written //But it’s not complete yet }

Converter

public static void converterTest() { BiMap<Integer, String> biMap = HashBiMap.create(); biMap.put(1, “a”); biMap.put(2, “b”); biMap.put(3, “c”); Converter<Integer, String> converter = Maps.asConverter(biMap); System.out.println(converter.convert(1)); System.out.println(converter.reverse().convert(“b”)); }

Optional

Optional can avoid null of an Object. public static void nullable() { Optional<Integer> i = Optional.fromNullable(null); System.out.println(i.or(2)); // output 2, because is null System.out.println(i.get()); // IllegalStateException } public static void absent() { Optional<Integer> i = Optional.absent(); System.out.println(i.or(2)); // output 2, because value is absent System.out.println(i.get()); // IllegalStateException } public static void of() { Optional<Integer> i… Read More »

CacheBuilder

Below one is the nice cache scheme. Just to remind that LoadingCache is an abstract class, not a interface. So it can’t be wrote in lambda expression. public static void cacheBuilderCase() throws Exception { LoadingCache<Integer, String> memo = CacheBuilder.newBuilder().build( new CacheLoader<Integer, String>() { public String load(Integer key) throws Exception { return String.valueOf(key); } }); System.out.println(memo.get(1));… Read More »

Supplier memoization

Below code is a simple way for memoization: private String value; public String getValue() { if (value == null) { value = “abcd”; } return value; } This can be also wrote in Guava way: Supplier<String> memo = Suppliers.memoize(() -> { return “abcd”; // inside function }); System.out.println(memo.get()); // will call the function System.out.println(memo.get()); //… Read More »

Create ExecutorService and ListeningExecutorService

Executor is a interface, there is no way to create it. Normally, there are 2 ways to create ExecutorService: ExecutorService service = Executors.newFixedThreadPool(10); ExecutorService service = Executors.newSingleThreadExecutor(); Normally, use decorator to create ListeningExecutorService by ExecutorService: ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10)); Compared to Executor, ExecutorService has shutdown function. ExecutorService returns Future, ListeningExecutorService returns ListenableFuture. Compared to Future, ListenableFuture can… Read More »

submit, execute, callable, runnable

ExecutorService and ListeningExecutorService has submit() and execute() funciton: Future<T> submit(Callable<T> task) Future<?> submit(Runnable task) void execute(Runnable command) Both ExecutorService and ListeningExecutorService can submit a Runnable and Callable parameter. Submit a Callable: public static void submitCallable() throws Exception{ ExecutorService executorService = Executors.newSingleThreadExecutor(); Callable<String> r = () -> { return “abcd”; }; Future<String> future = executorService.submit(r); System.out.println(future.get());… Read More »

Stop ExecutorService

Look at this code, it won’t stop: public static void main(String[] args) throws Exception{ ExecutorService executorService = Executors.newSingleThreadExecutor(); Runnable r = () -> { System.out.println(1); }; executorService.submit(r); } Main reason is that it didn’t call executorService.shutdown(); Exector is a simple interface. It only has a execute() function. ExecutorService has shutdown() function, which can stop the… Read More »