Java Flashcards
An applet
a small program that is intended not to be run on its own, but rather to be embedded inside another application.
How to convert JSON string into List of Java object?
mapper.readValue(jsonString, new TypeReference<>(){});
for each Map
for(Map.Entry entry: map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
Create class without new in Java
Class ref = Class.forName("CIBuildStatusInfo"); CIBuildStatusInfo obj = (CIBuildStatusInfo) ref.newInstance();
BiFunction / Supplier / Consumer ???
// два параметра, возвращает результат BiFunction { R apply(T t, U u); } // два параметра, не возвращает результат BiConsumer { void accept(T t, U u) } // один параметр, возвращает результат Function { R apply(T t); } // один параметр, не возвращает результат Consumer { void accept(T t); } // Без параметров, возвращает результат Supplier { T get(); }
возвращает результат немедленно. Если результат еще не записан, возвращает значение параметра valueIfAbsent. [threads][method]
T getNow(T valueIfAbsent)
runAsync / supplyAsync - difference ?
static <u> CompletableFuture<u> supplyAsync(Supplier<u> supplier)</u></u></u>
static CompletableFuture runAsync(Runnable runnable)
</u></u></u>
Основной метод. Имеет на входе два фьючерса, результаты которых накапливаются и затем передаются в реакцию, являющейся функцией от двух параметров.
<u> CompletableFuture thenCombine(CompletionStage other, BiFunction fn)
</u>
Перехват ошибок исполнения
CompletableFuture exceptionally(Function fn)
В этом методе реакция вызывается всегда, независимо от того, заваершился ли данный фьючерс нормально или аварийно. Если фьючерс завершился нормально с результатом r, то в реакцию будут переданы параметры (r, null), если аварийно с исключением ex, то в реакцию будут переданы параметры (null, ex). Результат реакции может быть другого типа, нежели результат данного фьючерса.
<u> CompletableFuture<u> handle(BiFunction fn)</u></u>
</u></u>
how to create ExecutorService and ScheduledExecutorService ???
ScheduledExecutorService executorService = Executors .newSingleThreadScheduledExecutor();
Difference between: scheduleAtFixedRate and scheduleWithFixedDelay ?
FixedRate - will be executed after time delay even if previous task has not been finished yet
FixedDelay - wait till previous task will be finished, wait delay time and start new one
@Schedule(cron=”* * * * *”) - tell a bit more about it?
restTemplate ??? how to make requests
restTemplate.getForObject(url, List.class);
Скільки існує станів потоків?
6: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
How to create thread and run it?
new Thread(new C()).start(); C should implement Runnable
How to give name of thread? (as parameter) we have new MyCustomThread() that implement Runnable
new Thread(new MyCustomThread(), “name”).start()
Що таке мьютекс?
взаимное исключение, примитив синхронизации, обеспечивающий защиту определенного обьєкта в потоке от доступа других потоков
What is synchronized
and how it is used?
So, if we use synchronized in method, it means that only one thread can get access to the method at the same time. When we use without it, every thread has access to it
Що таке семафор?
примитив синхронизации работи процесов и потоков в основе которого лежит счетчик
What is Callable?
Callable - it is a better version of Runnable. Appears in Java 5.
Callable c = () -> {… should return V}
Tell about interface Future
has 5 methods boolean cancel(boolean mayInterruptIfRunning); boolean isCancelled(); boolean isDone(); V get(); V get(long timeout, TimeUnit unit);
What shouldn’t we forget to do while working with ExecutorService?
executorService.shutdown();
Callable and we don’t want to return anything
Callable c = () -> {
…
return null;
}