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;
}
What is TreadPool?
пул тотоков, представляет собой группу робочих потоков которие виолняют задачи. If there is no available thread, our task stands in queue and wait till a thread will be available.
Types of Executors???
SingleThreadExecutor
FixedThreadPool(n)
CachedThreadPool
ScheduledExecutor
Cached - 60 seconds and dead
Framework Fork / Join
it is a framework for solving problems with using parallel approach “divide and conquer”
ComletableFuture vs Future
Future не можна закінчити вручну
Неможливо виконувати багато Future один за одним
Неможливо об’єднувати декілька Future
There is no exception handling
java.util.function
Consumer return void Function return R Supplier return T BiFunction return R BiConsumer
Exception handling in ComletalbeFuture
handle, whenComplete, exceptionally / exceptionallyCompose
List list = new ArrayList(); default value?
Object
usual names for generic types in java?
The most commonly used type parameter names are:
E — Element
K — Key
N — Number
T — Type
V — Value
S, U, V etc. — second, third, and fourth types
List - why is it wrong?
we can’t use primitive types in generics
how to create a method with generic parameter without generic class declaration in Java?
public int getCount(List elements) {
return elements.size();
}
what is wildcard in Java?
wildcard character (?) is used to indicate unknown type
What is cascade=CascadeType.ALL in Spring JPA?
it means all changes that were applied to one table, reflect on another (for relations oneToMany and manyToOne)