SlideShare a Scribd company logo
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Developer Advocate @JFrog
@jbaruch on the internetz
Solution Architect @Confluent
@gAmUssA on the internetz
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
@tagir_valeev
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
1. Two entertaining guys on
the stage
2. Funny puzzling questions
3. You think and vote
4.T-shirts are airborne
5. Official twitter hashtag:
#javapuzzlersng
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Which Java version are you on?
A. Java 7
B. Java 8
C. Java 9
D. Java 6
E. Java 5
F. Java 2
@jbaruch http://jfrog.com/shownotes @gamussa
Watching the puzzlers like… #dafaq
@jbaruch http://jfrog.com/shownotes @gamussa
Everything works (or doesn't)
in the latest Java 8 and/or 9 update
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
public class PerfectRobbery {
private Semaphore bankAccount = new Semaphore(-42);
public static void main(String[] args) {
PerfectRobbery perfectRobbery = new PerfectRobbery();
perfectRobbery.takeAllMoney();
perfectRobbery.checkBalance();
}
public void takeAllMoney(){
bankAccount.drainPermits();
}
public void checkBalance(){
System.out.println(bankAccount.availablePermits());
}
}
A. IllegalArgumentException –can’t create semaphore with negative
B. UnsupportedOperationException –can’t drain when negative
C. 0
D. -42
@jbaruch http://jfrog.com/shownotes @gamussa
A. IllegalArgumentException –can’t create semaphore with negative
B. UnsupportedOperationException –can’t drain when negative
C. 0
D. -42
public class PerfectRobbery {
private Semaphore bankAccount = new Semaphore(-42);
public static void main(String[] args) {
PerfectRobbery perfectRobbery = new PerfectRobbery();
perfectRobbery.takeAllMoney();
perfectRobbery.checkBalance();
}
public void takeAllMoney(){
bankAccount.drainPermits();
}
public void checkBalance(){
System.out.println(bankAccount.availablePermits());
}
}
Available
-42?!
@jbaruch http://jfrog.com/shownotes @gamussa
Available
-42?!
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
A. true/true
B. true/false
C. false/true
D. false/false
Collections.emptyList() == Collections.emptyList();
Collections.emptyIterator() == Collections.emptyIterator();
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
A. true/true
B. true/false
C. false/true
D. false/false
Spliterators.emptySpliterator() == Spliterators.emptySpliterator();
Stream.empty() == Stream.empty();
Singleton Strikes Back!
@jbaruch http://jfrog.com/shownotes @gamussa
A. true/true
B. true/false
C. false/true
D. false/false
Spliterators.emptySpliterator() == Spliterators.emptySpliterator();
Stream.empty() == Stream.empty();
@jbaruch http://jfrog.com/shownotes @gamussa
Even empty Stream has state!
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
”Identical”
1. Has the same state
2. Not related to “equals and hashcode”contract
3. Not related to references to objects in memory
@jbaruch http://jfrog.com/shownotes @gamussa
List[] twins = new List[2];
Arrays.setAll(twins, ArrayList::new);
A. Absolutely identical empty lists
B. Absolutely identical non-empty lists
C. Non-identical empty lists
D. Non-identical non-empty lists
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
List[] twins = new List[2];
Arrays.setAll(twins, ArrayList::new);
A. Absolutely identical empty lists
B. Absolutely identical non-empty lists
C. Non-identical empty lists
D. Non-identical non-empty lists
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
How single is a Single Abstract Method Interface?
@jbaruch http://jfrog.com/shownotes @gamussa
A. WTF?! ’Single’means one,not three!
B. Problem is with partyHard(T),remove it and it will work
C. Problem is the drinkIn methods,removing one of them and it will
work
D. It will work fine! Both partyHard() and drinkIn() are merged in
SingleAndHappy,leaving one abstract method
public interface Single<T> {
default void partyHard(String songName) { System.out.println(songName); }
void partyHard(T songName);
void drinkIn(T drinkName);
void drinkIn(String dringName);
}
@FunctionalInterface
public interface SingleAndHappy extends Single<String> { }
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A. WTF?! ’Single’means one,not three!
B. Problem is with partyHard(T),remove it and it will work
C. Problem are the drinkIn methods,removing it will leave one abstract
method
D. Yes! Both partyHard() and drinkIn() are merged in SingleAndHappy,
leaving one abstract method
public interface Single<T> {
default void partyHard(String songName) { System.out.println(songName); }
void partyHard(T songName);
void drinkIn(T drinkName);
void drinkIn(String dringName);
}
@FunctionalInterface
public interface SingleAndHappy extends Single<String> { }
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Hacking the bank
☑Bank software written in Java
☑Hack into it
☑Analyze the accounts
@jbaruch http://jfrog.com/shownotes @gamussa
Given the code above,which statement is wrong:
A. The Set is ordered by hashcode
B. The order is predictable across multiple runs of the JVM on the same machine
C. The order of elements in Set is not predictable
D. Statements A & B are correct
Set<String>	accounts=	new	HashSet<>(Arrays.asList("Gates",	"Buffett",	"Bezos",	"Zuckerberg"));
System.out.println(”accounts=	"	+	accounts);
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Given the code above,which statement is wrong:
A. The Set is ordered
B. The order is predictable across multiple runs of the JVM on the same machine
C. The order of elements in Set is not predictable
D. Statements A & B are correct
Set<String>	accounts=	new	HashSet<>(Arrays.asList("Gates",	"Buffett",	"Bezos",	"Zuckerberg"));
System.out.println(”accounts=	"	+	accounts);
@jbaruch http://jfrog.com/shownotes @gamussa
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
@jbaruch http://jfrog.com/shownotes @gamussa
Your turn,FBI
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
Given the code above,which statement is wrong:
A. The Set is ordered
B. The order is predictable across multiple runs of the JVM on the same machine
C. The order of elements in Set is not predictable
D. Statements A & B are correct
Set<String>	accounts	=	Set.of("Gates",	"Buffett",	"Bezos",	"Zuckerberg");
System.out.println(”accounts=	"	+	accounts);
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
Given the code above,which statement is wrong:
A. The Set is ordered
B. The order is predictable across multiple runs of the JVM on the same machine
C. The order of elements in Set is not predictable
D. Statements A & B are correct
Set<String>	accounts	=	Set.of("Gates",	"Buffett",	"Bezos",	"Zuckerberg");
System.out.println(”accounts=	"	+	accounts);
@jbaruch http://jfrog.com/shownotes @gamussa
private int probe(Object pe) {
int idx = Math.floorMod(pe.hashCode() ^ SALT, elements.length);
while (true) {
E ee = elements[idx];
if (ee == null) {
return -idx - 1;
} else if (pe.equals(ee)) {
return idx;
} else if (++idx == elements.length) {
idx = 0;
}
}
}
@jbaruch http://jfrog.com/shownotes @gamussa
Juggling Accident
What’s correct?
A. If you convert your application to module,classpath
dependencies will still be resolved correctly
B. If one of the dependencies was converted to a module,you
have to declare it in module-info in order to use
C. Once you added the module-info to your project you have to
declare the dependencies twice,in classpath and in module-
info
D. None of the above
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
What’s correct?
A. If you convert your application to module,classpath
dependencies will still be resolved correctly
B. If one of the dependencies was converted to a module,you
have to declare it in module-info in order to use
C. Once you added the module-info to your project you have to
declare the dependencies twice,in classpath and in module-
info
D. None of the above
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A. You killed them all
B. You killed only even ones
C. They all survived
D. You killed only odd ones
E. All answers are correct
static void killThemAll(Collection<Hero> expendables) {
Iterator<Hero> heroes = expendables.iterator();
heroes.forEachRemaining(e -> {
if (heroes.hasNext()) {
heroes.next();
heroes.remove();
}
});
System.out.println(expendables);
}
@jbaruch http://jfrog.com/shownotes @gamussa
A. You killed them all
B. You killed only even ones
C. They all survived
D. You killed only odd ones
E. All answers are correct
static void killThemAll(Collection<Hero> expendables) {
Iterator<Hero> heroes = expendables.iterator();
heroes.forEachRemaining(e -> {
if (heroes.hasNext()) {
heroes.next();
heroes.remove();
}
});
System.out.println(expendables);
}
Don’t do that.Really,don’t.
killThemAll(new ArrayList<String>(Arrays.asList("N","S","W","S","L","S","L","V")));
[]
killThemAll(new LinkedList<String>(Arrays.asList("N","S","W","S","L","S","L","V")));
[S,S,S,V]
killThemAll(new ArrayDeque<String>(Arrays.asList("N","S","W","S","L","S","L","V")));
[N,S,W,S,L,S,L,V]
killThemAll(new TreeSet<String>(Arrays.asList("N","S","W","S","L","S","L","V")));
[N,W,L,L]
@jbaruch http://jfrog.com/shownotes @gamussa
Subtle Difference
@jbaruch http://jfrog.com/shownotes @gamussa
A. Both work just fine
B. Lambda works,method ref fails
C. Method ref works,lambda fails
D. Won’t compile
@FunctionalInterface
public interface OriginalPredicate<T> {
boolean test(T t);
}
OriginalPredicate<Object> lambda = (Object obj) -> ”adidas".equals(obj);
OriginalPredicate<Object> methodRef = ”adidas"::equals;
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A. Both work just fine
B. Lambda works,method ref fails
C. Method ref works,lambda fails
D. Not a functional interface,will fail on annotation processing
@FunctionalInterface
Public interface CopyCatPredicate {
<T> boolean test(T t);
}
CopyCatPredicate lambda = (Object obj) -> " adadas".equals(obj);
CopyCatPredicate methodRef = " adadas"::equals;
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A. Both work just fine
B. Lambda works,method ref fails
C. Method ref works,lambda fails
D. Not a functional interface,will fail on annotation processing
@FunctionalInterface
Public interface CopyCatPredicate {
<T> boolean test(T t);
}
CopyCatPredicate lambda = (Object obj) -> " adadas".equals(obj);
CopyCatPredicate methodRef = " adadas"::equals;
@jbaruch http://jfrog.com/shownotes @gamussa
A	generic	function	type	for	a	functional	interface	may	be	implemented	by	a	
method	reference	expression	(§15.13),	but	not	by	a	lambda	expression	
(§15.27)	as	there	is	no	syntax	for	generic	lambda	expressions.	“
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A.[Data, Kirk, Spock]
B.[Spock, Kirk, Data, Data, Kirk, Spock]
C.[Spock, Kirk, Data]
D.[Data, Data, Kirk, Kirk, Spock, Spock]
E.Are you nuts? Won’t compile! Data with
Kirk?!
List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk",
"Spock").sequential()
.filter(new TreeSet<>()::add).collect(Collectors.toList());
System.out.println(list);
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A.[Data, Kirk, Spock]
B.[Spock, Kirk, Data, Data, Kirk, Spock]
C.[Spock, Kirk, Data]
D.[Data, Data, Kirk, Kirk, Spock, Spock]
E.Are you nuts? Won’t compile! Data with
Kirk?!
List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk",
"Spock").sequential()
.filter(new TreeSet<>()::add).collect(Collectors.toList());
System.out.println(list);
@jbaruch http://jfrog.com/shownotes @gamussa
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group
A.[Data, Kirk, Spock]
B.[Spock, Kirk, Data, Data, Kirk, Spock]
C.[Spock, Kirk, Data]
D.[Data, Data, Kirk, Kirk, Spock, Spock]
E.Are you nuts? Won’t compile! Data with
Kirk?!
List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk",
"Spock").sequential()
.filter(new TreeSet<>()::add).collect(Collectors.toList());
System.out.println(list);
@jbaruch http://jfrog.com/shownotes @gamussa
filter(new TreeSet<>()::add) filter(i -> new TreeSet<>().add(i))!=
New	instance	is	
created	every	time!
Instance	method	is	
created	once!
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
A. obvious / obvious
B. obvious / NullPointerException
C. NullPointerException / obvious
D. NullPointerException / NullPointerException
Optional.of("obvious").orElseGet(null);
Optional.empty().map(null).orElse("obvious");
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
A. obvious / obvious
B. obvious / NullPointerException
C. NullPointerException / obvious
D. NullPointerException / NullPointerException
Optional.of("obvious").orElseGet(null);
Optional.empty().map(null).orElse("obvious");
Will	never	happen
Will	never	happen
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
A. obvious / obvious
B. obvious / NullPointerException
C. NullPointerException / obvious
D. NullPointerException / NullPointerException
Optional.of("obvious").orElseGet(null);
Optional.empty().map(null).orElse("obvious");
@jbaruch http://jfrog.com/shownotes @gamussa
@jbaruch http://jfrog.com/shownotes @gamussa
Identical?
@jbaruch http://jfrog.com/shownotes @gamussa
A. All
B. 3 and 4
C. Only 3
D. Other
1. Consumer<String> agentA = s -> System.out.println(s);
Consumer<String> agentB = s -> System.out.println(s);
2. Consumer<String> agentA = System.out::println;
Consumer<String> agentB = System.out::println;
3. Supplier<Consumer<String>> supplier = () -> s -> System.out.println(s);
Consumer<String> agentA = supplier.get();
Consumer<String> agentB = supplier.get();
4. Supplier<Consumer<String>> supplier = () -> System.out::println;
Consumer<String> agentA = supplier.get();
Consumer<String> agentB = supplier.get();
When agentA == agentB?
@jbaruch http://jfrog.com/shownotes @gamussa
A. All
B. 3 and 4
C. Only 3
D. Other
1. Consumer<String> agentA = s -> System.out.println(s);
Consumer<String> agentB = s -> System.out.println(s);
2. Consumer<String> agentA = System.out::println;
Consumer<String> agentB = System.out::println;
3. Supplier<Consumer<String>> supplier = () -> s -> System.out.println(s);
Consumer<String> agentA = supplier.get();
Consumer<String> agentB = supplier.get();
4. Supplier<Consumer<String>> supplier = () -> System.out::println;
Consumer<String> agentA = supplier.get();
Consumer<String> agentB = supplier.get();
When agentA == agentB?
Reuse is only possible for pure functions
Consumers accept parameters == have
state
Supplier in 4 has state –the resolved
method reference
@jbaruch http://jfrog.com/shownotes @gamussa
Conclusions
@jbaruch http://jfrog.com/shownotes @gamussa
-Write readable code!
-Comment all the tricks
-Sometimes it’s just a bug
-Static code analysis FTW -
IntelliJ IDEA!
-RTFM!
-Don’t abuse lambdas and
streams!
-Trust us, we have much
more where those came
from.
-Puzzlers? Gotchas? Fetal
position inducing behavior?
-puzzlers@jfrog.com
-Shownotes!
-http://jfrog.com/shownotes
-Slides
-Video in 24 hours
-Links
-Ratings
-Raffle! (come early)
-Did you like it?
-Praise us on twitter!
-#javapuzzlersng
-@gamussa
-@jbaruch
-Didn’t like it?
-/dev/null

More Related Content

PDF
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
PDF
Java Puzzlers NG S02: Down the Rabbit Hole as presented at Devoxx US 2017
PDF
Testing Grails 3, the goob (unit), the bad (integration) and the ugly (functi...
PDF
Java 8 Puzzlers as it was presented at Codemash 2017
PDF
Java Puzzlers NG as it was presented at Detroit Java User Group
PDF
Espresso devoxx 2014
PDF
Are statecharts the next big UI paradigm?
PDF
Java Puzzlers NG S03 a DevNexus 2018
Java Puzzlers NG S02: Down the Rabbit Hole as presented at DevNexus 2017
Java Puzzlers NG S02: Down the Rabbit Hole as presented at Devoxx US 2017
Testing Grails 3, the goob (unit), the bad (integration) and the ugly (functi...
Java 8 Puzzlers as it was presented at Codemash 2017
Java Puzzlers NG as it was presented at Detroit Java User Group
Espresso devoxx 2014
Are statecharts the next big UI paradigm?
Java Puzzlers NG S03 a DevNexus 2018

Similar to Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group (20)

PPTX
Meetup django common_problems(1)
PPT
Django O/R Mapper
PPTX
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
PPT
Programming with Java: the Basics
PDF
[Philly ETE] Java Puzzlers NG
ODP
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
PDF
Starting Out With Java From Control Structures Through Data Structures 2nd Ed...
PDF
Starting Out With Java From Control Structures Through Data Structures 2nd Ed...
PPT
Mockito with a hint of PowerMock
PDF
Starting Out with Java From Control Structures through Objects 6th Edition Ga...
PDF
JavaOne 2013: Java 8 - The Good Parts
PDF
Java 8: the good parts!
ODP
ActiveWeb: Chicago Java User Group Presentation
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
PPT
Groovy Basics
PPT
course slides -- powerpoint
PPT
Django
PDF
Meerut Golden.pdf
PDF
Spring Certification Questions
PPTX
Generics On The JVM (What you don't know will hurt you)
Meetup django common_problems(1)
Django O/R Mapper
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Programming with Java: the Basics
[Philly ETE] Java Puzzlers NG
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Starting Out With Java From Control Structures Through Data Structures 2nd Ed...
Starting Out With Java From Control Structures Through Data Structures 2nd Ed...
Mockito with a hint of PowerMock
Starting Out with Java From Control Structures through Objects 6th Edition Ga...
JavaOne 2013: Java 8 - The Good Parts
Java 8: the good parts!
ActiveWeb: Chicago Java User Group Presentation
Java 8, Streams & Collectors, patterns, performances and parallelization
Groovy Basics
course slides -- powerpoint
Django
Meerut Golden.pdf
Spring Certification Questions
Generics On The JVM (What you don't know will hurt you)
Ad

More from Baruch Sadogursky (20)

PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
PDF
Data driven devops as presented at QCon London 2018
PDF
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
PDF
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
PDF
Data driven devops as presented at Codemash 2018
PDF
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
PPTX
Best Practices for Managing Docker Versions as presented at JavaOne 2017
PDF
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
PPTX
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
PDF
Let’s Wing It: A Study in DevRel Strategy
PDF
Log Driven First Class Customer Support at Scale
PPTX
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
PDF
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...
PDF
Groovy Puzzlers S04: The Bytecode Bites Back at Gr8Conf US 2017
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Gr8Conf 2017
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
Data driven devops as presented at QCon London 2018
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
Data driven devops as presented at Codemash 2018
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
Best Practices for Managing Docker Versions as presented at JavaOne 2017
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
Let’s Wing It: A Study in DevRel Strategy
Log Driven First Class Customer Support at Scale
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...
Groovy Puzzlers S04: The Bytecode Bites Back at Gr8Conf US 2017
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Gr8Conf 2017
Ad

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Big Data Technologies - Introduction.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
KodekX | Application Modernization Development
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Machine learning based COVID-19 study performance prediction
PPT
Teaching material agriculture food technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MYSQL Presentation for SQL database connectivity
Mobile App Security Testing_ A Comprehensive Guide.pdf
Spectral efficient network and resource selection model in 5G networks
Understanding_Digital_Forensics_Presentation.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Big Data Technologies - Introduction.pptx
Network Security Unit 5.pdf for BCA BBA.
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Empathic Computing: Creating Shared Understanding
KodekX | Application Modernization Development
Per capita expenditure prediction using model stacking based on satellite ima...
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsburgh Java Meetup Group

  • 3. Developer Advocate @JFrog @jbaruch on the internetz Solution Architect @Confluent @gAmUssA on the internetz
  • 9. 1. Two entertaining guys on the stage 2. Funny puzzling questions 3. You think and vote 4.T-shirts are airborne 5. Official twitter hashtag: #javapuzzlersng
  • 11. Which Java version are you on? A. Java 7 B. Java 8 C. Java 9 D. Java 6 E. Java 5 F. Java 2 @jbaruch http://jfrog.com/shownotes @gamussa
  • 12. Watching the puzzlers like… #dafaq @jbaruch http://jfrog.com/shownotes @gamussa
  • 13. Everything works (or doesn't) in the latest Java 8 and/or 9 update @jbaruch http://jfrog.com/shownotes @gamussa
  • 16. public class PerfectRobbery { private Semaphore bankAccount = new Semaphore(-42); public static void main(String[] args) { PerfectRobbery perfectRobbery = new PerfectRobbery(); perfectRobbery.takeAllMoney(); perfectRobbery.checkBalance(); } public void takeAllMoney(){ bankAccount.drainPermits(); } public void checkBalance(){ System.out.println(bankAccount.availablePermits()); } } A. IllegalArgumentException –can’t create semaphore with negative B. UnsupportedOperationException –can’t drain when negative C. 0 D. -42
  • 18. A. IllegalArgumentException –can’t create semaphore with negative B. UnsupportedOperationException –can’t drain when negative C. 0 D. -42 public class PerfectRobbery { private Semaphore bankAccount = new Semaphore(-42); public static void main(String[] args) { PerfectRobbery perfectRobbery = new PerfectRobbery(); perfectRobbery.takeAllMoney(); perfectRobbery.checkBalance(); } public void takeAllMoney(){ bankAccount.drainPermits(); } public void checkBalance(){ System.out.println(bankAccount.availablePermits()); } }
  • 22. A. true/true B. true/false C. false/true D. false/false Collections.emptyList() == Collections.emptyList(); Collections.emptyIterator() == Collections.emptyIterator(); @jbaruch http://jfrog.com/shownotes @gamussa
  • 24. A. true/true B. true/false C. false/true D. false/false Spliterators.emptySpliterator() == Spliterators.emptySpliterator(); Stream.empty() == Stream.empty();
  • 25. Singleton Strikes Back! @jbaruch http://jfrog.com/shownotes @gamussa
  • 26. A. true/true B. true/false C. false/true D. false/false Spliterators.emptySpliterator() == Spliterators.emptySpliterator(); Stream.empty() == Stream.empty(); @jbaruch http://jfrog.com/shownotes @gamussa
  • 27. Even empty Stream has state! @jbaruch http://jfrog.com/shownotes @gamussa
  • 29. ”Identical” 1. Has the same state 2. Not related to “equals and hashcode”contract 3. Not related to references to objects in memory @jbaruch http://jfrog.com/shownotes @gamussa
  • 30. List[] twins = new List[2]; Arrays.setAll(twins, ArrayList::new); A. Absolutely identical empty lists B. Absolutely identical non-empty lists C. Non-identical empty lists D. Non-identical non-empty lists @jbaruch http://jfrog.com/shownotes @gamussa
  • 32. List[] twins = new List[2]; Arrays.setAll(twins, ArrayList::new); A. Absolutely identical empty lists B. Absolutely identical non-empty lists C. Non-identical empty lists D. Non-identical non-empty lists @jbaruch http://jfrog.com/shownotes @gamussa
  • 34. How single is a Single Abstract Method Interface? @jbaruch http://jfrog.com/shownotes @gamussa
  • 35. A. WTF?! ’Single’means one,not three! B. Problem is with partyHard(T),remove it and it will work C. Problem is the drinkIn methods,removing one of them and it will work D. It will work fine! Both partyHard() and drinkIn() are merged in SingleAndHappy,leaving one abstract method public interface Single<T> { default void partyHard(String songName) { System.out.println(songName); } void partyHard(T songName); void drinkIn(T drinkName); void drinkIn(String dringName); } @FunctionalInterface public interface SingleAndHappy extends Single<String> { } @jbaruch http://jfrog.com/shownotes @gamussa
  • 37. A. WTF?! ’Single’means one,not three! B. Problem is with partyHard(T),remove it and it will work C. Problem are the drinkIn methods,removing it will leave one abstract method D. Yes! Both partyHard() and drinkIn() are merged in SingleAndHappy, leaving one abstract method public interface Single<T> { default void partyHard(String songName) { System.out.println(songName); } void partyHard(T songName); void drinkIn(T drinkName); void drinkIn(String dringName); } @FunctionalInterface public interface SingleAndHappy extends Single<String> { } @jbaruch http://jfrog.com/shownotes @gamussa
  • 40. Hacking the bank ☑Bank software written in Java ☑Hack into it ☑Analyze the accounts @jbaruch http://jfrog.com/shownotes @gamussa
  • 41. Given the code above,which statement is wrong: A. The Set is ordered by hashcode B. The order is predictable across multiple runs of the JVM on the same machine C. The order of elements in Set is not predictable D. Statements A & B are correct Set<String> accounts= new HashSet<>(Arrays.asList("Gates", "Buffett", "Bezos", "Zuckerberg")); System.out.println(”accounts= " + accounts); @jbaruch http://jfrog.com/shownotes @gamussa
  • 43. Given the code above,which statement is wrong: A. The Set is ordered B. The order is predictable across multiple runs of the JVM on the same machine C. The order of elements in Set is not predictable D. Statements A & B are correct Set<String> accounts= new HashSet<>(Arrays.asList("Gates", "Buffett", "Bezos", "Zuckerberg")); System.out.println(”accounts= " + accounts); @jbaruch http://jfrog.com/shownotes @gamussa
  • 44. public boolean add(E e) { return map.put(e, PRESENT)==null; } @jbaruch http://jfrog.com/shownotes @gamussa
  • 47. Given the code above,which statement is wrong: A. The Set is ordered B. The order is predictable across multiple runs of the JVM on the same machine C. The order of elements in Set is not predictable D. Statements A & B are correct Set<String> accounts = Set.of("Gates", "Buffett", "Bezos", "Zuckerberg"); System.out.println(”accounts= " + accounts); @jbaruch http://jfrog.com/shownotes @gamussa
  • 50. Given the code above,which statement is wrong: A. The Set is ordered B. The order is predictable across multiple runs of the JVM on the same machine C. The order of elements in Set is not predictable D. Statements A & B are correct Set<String> accounts = Set.of("Gates", "Buffett", "Bezos", "Zuckerberg"); System.out.println(”accounts= " + accounts); @jbaruch http://jfrog.com/shownotes @gamussa
  • 51. private int probe(Object pe) { int idx = Math.floorMod(pe.hashCode() ^ SALT, elements.length); while (true) { E ee = elements[idx]; if (ee == null) { return -idx - 1; } else if (pe.equals(ee)) { return idx; } else if (++idx == elements.length) { idx = 0; } } } @jbaruch http://jfrog.com/shownotes @gamussa
  • 53. What’s correct? A. If you convert your application to module,classpath dependencies will still be resolved correctly B. If one of the dependencies was converted to a module,you have to declare it in module-info in order to use C. Once you added the module-info to your project you have to declare the dependencies twice,in classpath and in module- info D. None of the above @jbaruch http://jfrog.com/shownotes @gamussa
  • 55. What’s correct? A. If you convert your application to module,classpath dependencies will still be resolved correctly B. If one of the dependencies was converted to a module,you have to declare it in module-info in order to use C. Once you added the module-info to your project you have to declare the dependencies twice,in classpath and in module- info D. None of the above @jbaruch http://jfrog.com/shownotes @gamussa
  • 58. A. You killed them all B. You killed only even ones C. They all survived D. You killed only odd ones E. All answers are correct static void killThemAll(Collection<Hero> expendables) { Iterator<Hero> heroes = expendables.iterator(); heroes.forEachRemaining(e -> { if (heroes.hasNext()) { heroes.next(); heroes.remove(); } }); System.out.println(expendables); }
  • 60. A. You killed them all B. You killed only even ones C. They all survived D. You killed only odd ones E. All answers are correct static void killThemAll(Collection<Hero> expendables) { Iterator<Hero> heroes = expendables.iterator(); heroes.forEachRemaining(e -> { if (heroes.hasNext()) { heroes.next(); heroes.remove(); } }); System.out.println(expendables); }
  • 61. Don’t do that.Really,don’t. killThemAll(new ArrayList<String>(Arrays.asList("N","S","W","S","L","S","L","V"))); [] killThemAll(new LinkedList<String>(Arrays.asList("N","S","W","S","L","S","L","V"))); [S,S,S,V] killThemAll(new ArrayDeque<String>(Arrays.asList("N","S","W","S","L","S","L","V"))); [N,S,W,S,L,S,L,V] killThemAll(new TreeSet<String>(Arrays.asList("N","S","W","S","L","S","L","V"))); [N,W,L,L] @jbaruch http://jfrog.com/shownotes @gamussa
  • 63. A. Both work just fine B. Lambda works,method ref fails C. Method ref works,lambda fails D. Won’t compile @FunctionalInterface public interface OriginalPredicate<T> { boolean test(T t); } OriginalPredicate<Object> lambda = (Object obj) -> ”adidas".equals(obj); OriginalPredicate<Object> methodRef = ”adidas"::equals;
  • 65. A. Both work just fine B. Lambda works,method ref fails C. Method ref works,lambda fails D. Not a functional interface,will fail on annotation processing @FunctionalInterface Public interface CopyCatPredicate { <T> boolean test(T t); } CopyCatPredicate lambda = (Object obj) -> " adadas".equals(obj); CopyCatPredicate methodRef = " adadas"::equals;
  • 67. A. Both work just fine B. Lambda works,method ref fails C. Method ref works,lambda fails D. Not a functional interface,will fail on annotation processing @FunctionalInterface Public interface CopyCatPredicate { <T> boolean test(T t); } CopyCatPredicate lambda = (Object obj) -> " adadas".equals(obj); CopyCatPredicate methodRef = " adadas"::equals;
  • 71. A.[Data, Kirk, Spock] B.[Spock, Kirk, Data, Data, Kirk, Spock] C.[Spock, Kirk, Data] D.[Data, Data, Kirk, Kirk, Spock, Spock] E.Are you nuts? Won’t compile! Data with Kirk?! List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk", "Spock").sequential() .filter(new TreeSet<>()::add).collect(Collectors.toList()); System.out.println(list); @jbaruch http://jfrog.com/shownotes @gamussa
  • 73. A.[Data, Kirk, Spock] B.[Spock, Kirk, Data, Data, Kirk, Spock] C.[Spock, Kirk, Data] D.[Data, Data, Kirk, Kirk, Spock, Spock] E.Are you nuts? Won’t compile! Data with Kirk?! List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk", "Spock").sequential() .filter(new TreeSet<>()::add).collect(Collectors.toList()); System.out.println(list); @jbaruch http://jfrog.com/shownotes @gamussa
  • 75. A.[Data, Kirk, Spock] B.[Spock, Kirk, Data, Data, Kirk, Spock] C.[Spock, Kirk, Data] D.[Data, Data, Kirk, Kirk, Spock, Spock] E.Are you nuts? Won’t compile! Data with Kirk?! List<String> list = Stream.of("Spock", "Kirk", "Data", "Data", "Kirk", "Spock").sequential() .filter(new TreeSet<>()::add).collect(Collectors.toList()); System.out.println(list); @jbaruch http://jfrog.com/shownotes @gamussa
  • 76. filter(new TreeSet<>()::add) filter(i -> new TreeSet<>().add(i))!= New instance is created every time! Instance method is created once! @jbaruch http://jfrog.com/shownotes @gamussa
  • 78. A. obvious / obvious B. obvious / NullPointerException C. NullPointerException / obvious D. NullPointerException / NullPointerException Optional.of("obvious").orElseGet(null); Optional.empty().map(null).orElse("obvious"); @jbaruch http://jfrog.com/shownotes @gamussa
  • 80. A. obvious / obvious B. obvious / NullPointerException C. NullPointerException / obvious D. NullPointerException / NullPointerException Optional.of("obvious").orElseGet(null); Optional.empty().map(null).orElse("obvious"); Will never happen Will never happen @jbaruch http://jfrog.com/shownotes @gamussa
  • 82. A. obvious / obvious B. obvious / NullPointerException C. NullPointerException / obvious D. NullPointerException / NullPointerException Optional.of("obvious").orElseGet(null); Optional.empty().map(null).orElse("obvious"); @jbaruch http://jfrog.com/shownotes @gamussa
  • 85. A. All B. 3 and 4 C. Only 3 D. Other 1. Consumer<String> agentA = s -> System.out.println(s); Consumer<String> agentB = s -> System.out.println(s); 2. Consumer<String> agentA = System.out::println; Consumer<String> agentB = System.out::println; 3. Supplier<Consumer<String>> supplier = () -> s -> System.out.println(s); Consumer<String> agentA = supplier.get(); Consumer<String> agentB = supplier.get(); 4. Supplier<Consumer<String>> supplier = () -> System.out::println; Consumer<String> agentA = supplier.get(); Consumer<String> agentB = supplier.get(); When agentA == agentB?
  • 87. A. All B. 3 and 4 C. Only 3 D. Other 1. Consumer<String> agentA = s -> System.out.println(s); Consumer<String> agentB = s -> System.out.println(s); 2. Consumer<String> agentA = System.out::println; Consumer<String> agentB = System.out::println; 3. Supplier<Consumer<String>> supplier = () -> s -> System.out.println(s); Consumer<String> agentA = supplier.get(); Consumer<String> agentB = supplier.get(); 4. Supplier<Consumer<String>> supplier = () -> System.out::println; Consumer<String> agentA = supplier.get(); Consumer<String> agentB = supplier.get(); When agentA == agentB?
  • 88. Reuse is only possible for pure functions Consumers accept parameters == have state Supplier in 4 has state –the resolved method reference @jbaruch http://jfrog.com/shownotes @gamussa
  • 90. -Write readable code! -Comment all the tricks -Sometimes it’s just a bug -Static code analysis FTW - IntelliJ IDEA! -RTFM! -Don’t abuse lambdas and streams!
  • 91. -Trust us, we have much more where those came from. -Puzzlers? Gotchas? Fetal position inducing behavior? -puzzlers@jfrog.com
  • 93. -Did you like it? -Praise us on twitter! -#javapuzzlersng -@gamussa -@jbaruch -Didn’t like it? -/dev/null