SlideShare a Scribd company logo
Silent Revolution by Max Voronoy (Senior Consultant, Engineering, Globallogic)
BAD MT EXAMPLES
try(Transaction t = db.startTransaction()){
List<User> all = db.select10000Users();
all.forEach(u->{
String text = template.formatEmail(u);
smtp.send(u.email, text);
});
}
Future<?> future = executorService.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
future.get();
• NO MT CODE
private Lock synchro = new ReentrantLock();
public void wrong2(Map<String, String> sharedResource)
{
synchro.lock();
try{
sharedResource.put("Key1", "Value1");
}finally {
synchro.unlock();
}
}
• ERROR IN PRIMITIVE USE
• ERROR IN RESPONSIBILITY AND TRANSACTION SCOPE
class Singleton //doublecheck
{
static volatile Singleton instance;
static Object accessor…
static Singleton get()
{
if(instance == null){
lock(accessor){
if(instance == null)
instance = new;
}
}
return instance;
}
}
• BROKEN PATTERN
WHERE IS MY CPU
• BAD CPU UTILIZATION
• NO LOAD RESERVE
EVERYBODY LIKES SPRING ( )
ReactiveX
Reactor IO
• NETTY, JETTY, TOMCAT, UNDERTOW (SERVLET 3.1 )
• JDK 9 AS JAVA.UTIL.CONCURRENT.FLOW
• > JAVA.NIO.FILE.*(AsynchronousFileChannel)
• HTTP | WEBSOCKET | TCP | UDP
Streams
THINK REACTIVE
event Iterable (pull) Observable (push)
retrieve data T next() onNext(T)
discover error throws Exception onError(Exception)
complete !hasNext() onCompleted()
BASIC PLAYERS (FROM REACTOR.IO)
• SUBSCRIBER
• PUBLISHER
• FLUX -> 0:N (∞)
• MONO -> 0:1
public void subscribe(Subscriber<? super T> s);
// Factory for Subscription interface
void onSubscribe(Subscription s);
void onNext(T t);
void onError(Throwable t);
void onComplete();
LET’S RUN SIMPLE
Flux.just("red", "white", "blue")
.log()
.map(value -> value.toUpperCase())
.subscribe(System.out::println);
Flux.just("red", "white", "blue")
.subscribeOn(Schedulers.parallel()) // !!!!
.log()
.map(value -> value.toUpperCase())
.subscribe(System.out::println);
01:37:18.678 [main] INFO reactor.core.publisher.FluxLog -
ON_SUBSCRIBE(reactor.core.publisher.FluxArray$ArraySubscription@35bbe5e8)
01:37:18.681 [main] INFO reactor.core.publisher.FluxLog - REQUEST(unbounded)
01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(red)
RED
01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(white)
WHITE
01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(blue)
BLUE
01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_COMPLETE()
...
17:26:15.184 [main] INFO reactor.Flux.SubscribeOn.1 - request(unbounded)
17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(red)
RED
17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(white)
WHITE
17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(blue)
BLUE
17:26:15.190 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onComplete()
COMPLICATED EXAMPLE@Document
class Person
{
@Id
String id;
String name;
}
interface PersonRepository
extends MongoRepository<Person, String>
{
@Query("{}")
Stream<Person> all();
CompletableFuture<Person> findById(String id);
}
@Controller
class PersonController
{
@Autowired
PersonRepository personRepository;
@GetMapping("/person")
public Flux<Person> all(){
return Flux.fromStream( personRepository.all() );
}
@GetMapping("/person/{id}")
public Mono<Person> byId(@PathVariable String userId){
return Optional
.ofNullable(userId)
.map(id -> personRepository.findById(id))
.map(person-> Mono.fromFuture(person))
.orElseThrow(() -> new IllegalStateException("error - null id"))
;
}
}
UNDER THE HOOD
Thread
HTTP
Request
Thread
HTTP
Request
100
. . .
@GetMapping("/person")
List<Person> get(){
List<Person> result =
db.longOperation();
return
Response.ok(result);
}
HTTP
HTTP
HTTPHTTP
HTTP
< 100
@GetMapping("/person")
public Flux<Person> all(){
return Flux.fromStream( personRepository.all() );
}
COMMON INTERVIEW MISTAKE
• ASYNC REQUEST AS AN ANSWER FOR LONG
REQUESTS (WRONG)
JavaScript queries
process
Long Running
server
Display results
• PULLING OR PUSHING (RIGHT)
Client query
Pull status of Job
Display Result
Server
Render Job ID
Track Status of Job
DO IT IN REACTIVE WAY
@RequestMapping(value = "/report/{userId}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)
public void longReport(@PathVariable String userId){
Mono.just(userId)
.subscribeOn(Schedulers.parallel()) // MOST IMPORTANT LINE
.log()
.subscribe(
personRepository::longOperation,
websocketRegistry::notifyError, //use WebSockets to report error
websocketRegistry::notifySuccess //use WebSockets to report success
);
;
//here we return to client status OK
}
{FINALIZE}
• REACTIVE REVOLUTIONIZE MULTITHREADING BY
EXPOSING GOOD DESIGN PATTERNS;
• SPRING PUTS ALL TOGETHER;
• CHANGE YOUR MIND TO BE REACTIVE.
• ANY QUESTIONS?

More Related Content

PDF
Data recovery using pg_filedump
TXT
Code
PDF
pg_filedump
PDF
Full Text Search in PostgreSQL
PDF
Java program-to-calculate-area-and-circumference-of-circle
PPT
FMDB - SLC-Cocoaheads
PDF
Groovy and Grails talk
PPT
Kill the DBA
Data recovery using pg_filedump
Code
pg_filedump
Full Text Search in PostgreSQL
Java program-to-calculate-area-and-circumference-of-circle
FMDB - SLC-Cocoaheads
Groovy and Grails talk
Kill the DBA

What's hot (20)

ZIP
iPhone and Rails integration
PDF
Understanding the nodejs event loop
PPTX
Functional Reactive Programming with RxJS
PDF
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
PDF
Talk KVO with rac by Philippe Converset
PDF
The Ring programming language version 1.5.4 book - Part 26 of 185
PDF
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
PPTX
Frozen Rails / 2004 vs. 2010
PDF
Interview C++11 code
PDF
Bristol 2009 q1_wright_steve
PPTX
LINKED LISTS
TXT
New text document
PDF
Algorithms devised for a google interview
PPTX
Config BuildConfig
PDF
Use C++ to Manipulate mozSettings in Gecko
TXT
Operator overloading (binary)
PDF
The Singleton Pattern In Java
PDF
Transducers in JavaScript
PPT
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
PDF
オープンデータを使ったモバイルアプリ開発(応用編)
iPhone and Rails integration
Understanding the nodejs event loop
Functional Reactive Programming with RxJS
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Talk KVO with rac by Philippe Converset
The Ring programming language version 1.5.4 book - Part 26 of 185
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Frozen Rails / 2004 vs. 2010
Interview C++11 code
Bristol 2009 q1_wright_steve
LINKED LISTS
New text document
Algorithms devised for a google interview
Config BuildConfig
Use C++ to Manipulate mozSettings in Gecko
Operator overloading (binary)
The Singleton Pattern In Java
Transducers in JavaScript
Realtime Analytics Using MongoDB, Python, Gevent, and ZeroMQ
オープンデータを使ったモバイルアプリ開発(応用編)
Ad

Similar to Silent Revolution by Max Voronoy (Senior Consultant, Engineering, Globallogic) (20)

PDF
A Deep Dive into Query Execution Engine of Spark SQL
PPTX
Apache Flink: API, runtime, and project roadmap
PDF
Presto anatomy
PDF
제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀
PPTX
Akka.NET streams and reactive streams
ODP
Stratosphere Intro (Java and Scala Interface)
PDF
Pdxpugday2010 pg90
PDF
Reactive programming on Android
PPTX
2 презентация rx java+android
PDF
For each task, submit your source java code file.(1) Objective Im.pdf
PPT
A brief introduction to PostgreSQL
PDF
Job Queue in Golang
PDF
[245] presto 내부구조 파헤치기
PDF
RxJava on Android
PDF
Performance Tuning Using oratop
PPTX
Flink Batch Processing and Iterations
PDF
Java 8 Workshop
PPTX
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
PPTX
Flink internals web
A Deep Dive into Query Execution Engine of Spark SQL
Apache Flink: API, runtime, and project roadmap
Presto anatomy
제 8회 엑셈 수요 세미나 자료 연구컨텐츠팀
Akka.NET streams and reactive streams
Stratosphere Intro (Java and Scala Interface)
Pdxpugday2010 pg90
Reactive programming on Android
2 презентация rx java+android
For each task, submit your source java code file.(1) Objective Im.pdf
A brief introduction to PostgreSQL
Job Queue in Golang
[245] presto 내부구조 파헤치기
RxJava on Android
Performance Tuning Using oratop
Flink Batch Processing and Iterations
Java 8 Workshop
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Flink internals web
Ad

More from GlobalLogic Ukraine (20)

PDF
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
PPTX
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
PDF
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
PDF
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
PDF
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
PPTX
Штучний інтелект як допомога в навчанні, а не замінник.pptx
PPTX
Задачі AI-розробника як застосовується штучний інтелект.pptx
PPTX
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
PDF
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
PDF
JavaScript Community Webinar #14 "Why Is Git Rebase?"
PDF
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
PPTX
Страх і сила помилок - IT Inside від GlobalLogic Education
PDF
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
PDF
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
PDF
“How to Secure Your Applications With a Keycloak?
PDF
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
PPTX
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
PDF
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
PDF
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
“How to Secure Your Applications With a Keycloak?
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"

Recently uploaded (20)

PDF
ETO & MEO Certificate of Competency Questions and Answers
PPTX
Strings in CPP - Strings in C++ are sequences of characters used to store and...
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
PDF
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
PPTX
web development for engineering and engineering
PDF
composite construction of structures.pdf
PPTX
AgentX UiPath Community Webinar series - Delhi
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Practice Questions on recent development part 1.pptx
PPTX
Internship_Presentation_Final engineering.pptx
DOCX
573137875-Attendance-Management-System-original
ETO & MEO Certificate of Competency Questions and Answers
Strings in CPP - Strings in C++ are sequences of characters used to store and...
Operating System & Kernel Study Guide-1 - converted.pdf
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
Structs to JSON How Go Powers REST APIs.pdf
BRKDCN-2613.pdf Cisco AI DC NVIDIA presentation
오픈소스 LLM, vLLM으로 Production까지 (Instruct.KR Summer Meetup, 2025)
web development for engineering and engineering
composite construction of structures.pdf
AgentX UiPath Community Webinar series - Delhi
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
Chapter 6 Design in software Engineeing.ppt
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Practice Questions on recent development part 1.pptx
Internship_Presentation_Final engineering.pptx
573137875-Attendance-Management-System-original

Silent Revolution by Max Voronoy (Senior Consultant, Engineering, Globallogic)

  • 2. BAD MT EXAMPLES try(Transaction t = db.startTransaction()){ List<User> all = db.select10000Users(); all.forEach(u->{ String text = template.formatEmail(u); smtp.send(u.email, text); }); } Future<?> future = executorService.submit(() -> { String threadName = Thread.currentThread().getName(); System.out.println("Hello " + threadName); }); future.get(); • NO MT CODE private Lock synchro = new ReentrantLock(); public void wrong2(Map<String, String> sharedResource) { synchro.lock(); try{ sharedResource.put("Key1", "Value1"); }finally { synchro.unlock(); } } • ERROR IN PRIMITIVE USE • ERROR IN RESPONSIBILITY AND TRANSACTION SCOPE class Singleton //doublecheck { static volatile Singleton instance; static Object accessor… static Singleton get() { if(instance == null){ lock(accessor){ if(instance == null) instance = new; } } return instance; } } • BROKEN PATTERN
  • 3. WHERE IS MY CPU • BAD CPU UTILIZATION • NO LOAD RESERVE
  • 4. EVERYBODY LIKES SPRING ( ) ReactiveX Reactor IO • NETTY, JETTY, TOMCAT, UNDERTOW (SERVLET 3.1 ) • JDK 9 AS JAVA.UTIL.CONCURRENT.FLOW • > JAVA.NIO.FILE.*(AsynchronousFileChannel) • HTTP | WEBSOCKET | TCP | UDP Streams
  • 5. THINK REACTIVE event Iterable (pull) Observable (push) retrieve data T next() onNext(T) discover error throws Exception onError(Exception) complete !hasNext() onCompleted()
  • 6. BASIC PLAYERS (FROM REACTOR.IO) • SUBSCRIBER • PUBLISHER • FLUX -> 0:N (∞) • MONO -> 0:1 public void subscribe(Subscriber<? super T> s); // Factory for Subscription interface void onSubscribe(Subscription s); void onNext(T t); void onError(Throwable t); void onComplete();
  • 7. LET’S RUN SIMPLE Flux.just("red", "white", "blue") .log() .map(value -> value.toUpperCase()) .subscribe(System.out::println); Flux.just("red", "white", "blue") .subscribeOn(Schedulers.parallel()) // !!!! .log() .map(value -> value.toUpperCase()) .subscribe(System.out::println); 01:37:18.678 [main] INFO reactor.core.publisher.FluxLog - ON_SUBSCRIBE(reactor.core.publisher.FluxArray$ArraySubscription@35bbe5e8) 01:37:18.681 [main] INFO reactor.core.publisher.FluxLog - REQUEST(unbounded) 01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(red) RED 01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(white) WHITE 01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_NEXT(blue) BLUE 01:37:18.682 [main] INFO reactor.core.publisher.FluxLog - ON_COMPLETE() ... 17:26:15.184 [main] INFO reactor.Flux.SubscribeOn.1 - request(unbounded) 17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(red) RED 17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(white) WHITE 17:26:15.189 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onNext(blue) BLUE 17:26:15.190 [parallel-1] INFO reactor.Flux.SubscribeOn.1 - onComplete()
  • 8. COMPLICATED EXAMPLE@Document class Person { @Id String id; String name; } interface PersonRepository extends MongoRepository<Person, String> { @Query("{}") Stream<Person> all(); CompletableFuture<Person> findById(String id); } @Controller class PersonController { @Autowired PersonRepository personRepository; @GetMapping("/person") public Flux<Person> all(){ return Flux.fromStream( personRepository.all() ); } @GetMapping("/person/{id}") public Mono<Person> byId(@PathVariable String userId){ return Optional .ofNullable(userId) .map(id -> personRepository.findById(id)) .map(person-> Mono.fromFuture(person)) .orElseThrow(() -> new IllegalStateException("error - null id")) ; } }
  • 9. UNDER THE HOOD Thread HTTP Request Thread HTTP Request 100 . . . @GetMapping("/person") List<Person> get(){ List<Person> result = db.longOperation(); return Response.ok(result); } HTTP HTTP HTTPHTTP HTTP < 100 @GetMapping("/person") public Flux<Person> all(){ return Flux.fromStream( personRepository.all() ); }
  • 10. COMMON INTERVIEW MISTAKE • ASYNC REQUEST AS AN ANSWER FOR LONG REQUESTS (WRONG) JavaScript queries process Long Running server Display results • PULLING OR PUSHING (RIGHT) Client query Pull status of Job Display Result Server Render Job ID Track Status of Job
  • 11. DO IT IN REACTIVE WAY @RequestMapping(value = "/report/{userId}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) public void longReport(@PathVariable String userId){ Mono.just(userId) .subscribeOn(Schedulers.parallel()) // MOST IMPORTANT LINE .log() .subscribe( personRepository::longOperation, websocketRegistry::notifyError, //use WebSockets to report error websocketRegistry::notifySuccess //use WebSockets to report success ); ; //here we return to client status OK }
  • 12. {FINALIZE} • REACTIVE REVOLUTIONIZE MULTITHREADING BY EXPOSING GOOD DESIGN PATTERNS; • SPRING PUTS ALL TOGETHER; • CHANGE YOUR MIND TO BE REACTIVE. • ANY QUESTIONS?