Dear Vishi, dear logs for today.
How to download Bing's background images? You can get the download url from JSON endpoint.
practical-reactor is a great repo to learn Project Reactor. First clone the repo
# Create a fork of the repo
# Clone the repo
cd practical-reactor
mvn clean install
Next open the folder in your IDE and look at problems at exercises/src/test/java
.
You can use block
on any publisher like
Mono<String> foo = Mono.just("hello");
// This will block until the value is available
String bar = foo.block();
// However, this is not recommended in reactive code since it blocks the thread
// If you want to block with a timeout, do it like this:
String fooBar = foo.block(Duration.ofSeconds(1));
When to use optional? Optional is mainly used to avoid NullPointerException (NPE).
// Creates an Optional with a non-null value
Optional<String> foo = Optional.of(someSequence);
// However, if someSequence is null, this will throw NPE
if (foo.isEmpty()) {
// ...
}
// Use ofNullable when the value could be null
Optional<String> bar = Optional.ofNullable(someSequence);
// This won’t throw NPE
if (bar.isEmpty()) {
// ...
}
.subscribe() is how you start processing a Flux or Mono. First case is fire and forget like
flux.subscribe();
You can also handle emitted values like
flux.subscribe(item -> {
// handle each item
System.out.println(item);
});
You can provide up to three callbacks: Handling Items, Errors, and Completion
flux.subscribe(
item -> { /* onNext: handle each item */ },
error -> { /* onError: handle errors */ },
() -> { /* onComplete: handle completion */ }
);
fortuneTop5()
.subscribe(
companyList::add, // onNext: add each item to the list
error -> {}, // onError: do nothing
() -> serviceCallCompleted.set(true) // onComplete: set flag
);
Distinction between OS threads, platform threads and virtual threads?
An OS thread is managed by the kernel of the operating system. It has its own stack. To switch between threads, the OS performs a context switch, which may involve a system call. A system call is an elevated request to access kernel space, since user-space applications cannot access kernel space directly.
In Java, a platform thread is a wrapper around an OS thread. It has a 1-to-1 mapping with an OS thread. So when we create a thread:
Thread thread = new Thread(() -> {});
it actually creates a corresponding OS thread.
A virtual thread (introduced with Project Loom) decouples the Java thread abstraction from platform threads. Virtual threads are scheduled by the JVM and can be multiplexed onto a smaller number of platform threads, allowing millions of virtual threads to exist efficiently while sharing the same pool of platform threads.