Posts Tagged ‘Java8’
[DevoxxUS2017] Java Puzzlers NG S02: Down the Rabbit Hole by Baruch Sadogursky and Viktor Gamov
At DevoxxUS2017, Baruch Sadogursky and Viktor Gamov, from JFrog and Hazelcast respectively, entertained attendees with a lively exploration of Java 8 and 9 puzzlers. Known for their engaging style, Baruch, a Developer Advocate, and Viktor, a Senior Solution Architect, presented complex coding challenges involving streams, lambdas, and Optionals. Their session combined humor, technical depth, and audience interaction, offering valuable lessons for Java developers. This post examines the key themes of their presentation, highlighting strategies to navigate Java’s intricacies.
Decoding Java 8 Complexities
Baruch Sadogursky and Viktor Gamov kicked off with a series of Java 8 puzzlers, focusing on streams and lambdas. They presented scenarios where seemingly simple code led to unexpected outcomes, such as subtle bugs in stream operations. Baruch emphasized the importance of understanding functional programming nuances, using examples to illustrate common pitfalls. Their interactive approach, with audience participation, made complex concepts accessible and engaging.
Navigating Java 9 Features
Transitioning to Java 9, Viktor explored new puzzlers involving modules and CompletableFutures, highlighting how these features introduce fresh challenges. He demonstrated how the module system can lead to compilation errors if misconfigured, urging developers to read documentation carefully. Their examples, drawn from real-world experiences at JFrog and Hazelcast, underscored the need for precision in adopting Java’s evolving features.
Tools for Avoiding Pitfalls
Baruch and Viktor stressed the role of tools like IntelliJ IDEA in catching errors early, noting how its inspections highlight potential issues in lambda and stream usage. They advised against overusing complex constructs, advocating for simplicity to avoid “WTF” moments. Their practical tips, grounded in their extensive conference-speaking experience, encouraged developers to leverage IDEs and documentation to write robust code.
Community Engagement and Resources
Concluding with a call to action, Baruch and Viktor invited developers to contribute puzzlers to JFrog’s puzzlers initiative, fostering community-driven learning. They shared resources, including their slide deck and blog posts, encouraging feedback via Twitter. Their enthusiasm for Java’s challenges inspired attendees to dive deeper into the language’s intricacies, embracing both its power and pitfalls.
Links:
[DevoxxFR2015] Harnessing Java 8: Building Real-Time Applications
Trisha Gee, a Java Champion and Developer Advocate at JetBrains, showcased the power of Java 8 at Devoxx France 2015 by live-coding a real-time dashboard application. With extensive experience in high-performance Java systems, Trisha demonstrated how streams, lambdas, and the new date/time API can create robust, end-to-end applications using core Java libraries.
Crafting a Real-Time Dashboard
Trisha kicked off by building a JavaFX-based dashboard that consumed a high-velocity data feed, simulating Twitter sentiment analysis. She leveraged Java 8 streams to process collections efficiently, transforming raw data into meaningful insights. Lambdas simplified code, replacing verbose loops with concise expressions. Her demo highlighted real-time updates, with the dashboard dynamically rendering mood data.
This approach, Trisha emphasized, showcases Java 8’s expressiveness.
Streamlining Data Manipulation
Using streams, Trisha demonstrated filtering and aggregating data to display sentiment trends. The joining collector automatically formatted outputs, eliminating manual string manipulation. She also touched on the new date/time API, ensuring precise temporal handling. Despite a glitch requiring a restart, the dashboard successfully visualized real-time Twitter data, proving Java 8’s suitability for dynamic applications.
Her live coding, Trisha noted, demystifies complex features.
JavaFX for Modern UIs
Trisha integrated JavaFX to create a responsive UI, binding data to visual components. She contrasted fake and real mood services, showing how streams handle both seamlessly. Q&A was limited due to time, but she shared a comprehensive resource page, including WebSocket and JavaFX references, encouraging further exploration.
This session positions Java 8 as a versatile tool for modern development.
Links:
[DevoxxBE2013] Part 1: Thinking Functional Style
Venkat Subramaniam, an award-winning author and founder of Agile Developer, Inc., guides developers through the paradigm shift of functional programming on the JVM. Renowned for Functional Programming in Java and his global mentorship, Venkat uses Java 8, Groovy, and Scala to illustrate functional tenets. His session contrasts imperative statements with composable expressions, demonstrating how to leverage lambda expressions and higher-order functions for elegant, maintainable code.
Functional programming, Venkat posits, transcends syntax—it’s a mindset fostering immutability and data flow. Through practical examples, he showcases Groovy’s idiomatic functional constructs and Scala’s expression-driven purity, equipping attendees to rethink application design.
Functional Principles and Expressions
Venkat contrasts statements—imperative, mutation-driven blocks—with expressions, which compute and return values. He demos a Java 8 stream pipeline, transforming data without side effects, versus a loop’s mutability.
Expressions, Venkat emphasizes, enable seamless composition, fostering cleaner, more predictable codebases.
Groovy’s Functional Idioms
Groovy, though not purely functional, excels in functional style, Venkat illustrates. He showcases collect and findAll for list transformations, akin to Java 8 streams, with concise closures.
These idioms, he notes, simplify data processing, making functional patterns intuitive for Java developers.
Scala’s Expression-Driven Design
Scala’s expression-centric nature shines in Venkat’s examples: every construct returns a value, enabling chaining. He demos pattern matching and for-comprehensions, streamlining complex workflows.
This purity, Venkat argues, minimizes state bugs, aligning with functional ideals.
Higher-Order Functions and Composition
Venkat explores higher-order functions, passing lambdas as arguments. A Groovy example composes functions to filter and map data, while Scala’s currying simplifies partial application.
Such techniques, he asserts, enhance modularity, enabling parallelization for performance-critical tasks.
Practical Adoption and Parallelization
Venkat advocates starting with small functional refactors, like replacing loops with streams. He demos parallel stream processing in Java 8, leveraging multi-core CPUs.
This pragmatic approach, he concludes, bridges imperative habits with functional elegance, boosting scalability.
Links:
[DevoxxBE2013] Lambda: A Peek Under the Hood
Brian Goetz, Java Language Architect at Oracle, offers an illuminating dissection of lambda expressions in Java SE 8, transcending syntactic sugar to reveal the sophisticated machinery powering this evolution. Renowned for Java Concurrency in Practice and leadership in JSR 335, Brian demystifies lambdas’ implementation atop invokedynamic from Java SE 7. His session, eschewing introductory fare, probes the VM’s strategies for efficiency, contrasting naive inner-class approaches with optimized bootstrapping and serialization.
Lambdas, Brian asserts, unlock expressive potential for applications and libraries, but their true prowess lies in performance rivaling or surpassing inner classes—without the bloat. Through benchmarks and code dives, he showcases flexibility and future-proofing, underscoring the iterative path to a robust design.
From Syntax to Bytecode: The Bootstrap Process
Brian traces lambdas’ lifecycle: source code desugars to invokedynamic callsites, embedding a “recipe” for instantiation. The bootstrap method, invoked once per callsite, crafts a classfile dynamically, caching for reuse.
This declarative embedding, Brian illustrates, avoids inner classes’ per-instance overhead, yielding leaner bytecode and faster captures—non-capturing lambdas hit 1.5x inner-class speeds in early benchmarks.
Optimization Strategies and Capture Semantics
Capturing lambdas, Brian explains, leverage local variable slots via synthetic fields, minimizing allocations. He contrasts “eager” (immediate class creation) with “lazy” (deferred) strategies, favoring the latter for reduced startup.
Invokedynamic’s dynamic binding enables profile-guided refinements, promising ongoing gains. Brian’s throughput metrics affirm lambdas’ edge, even in capturing scenarios.
Serialization and Bridge Methods
Serializing lambdas invokes writeReplace to a serialized form, preserving semantics without runtime overhead. Brian demos bridge methods for functional interfaces, ensuring compatibility.
Default methods, he notes, extend interfaces safely, avoiding binary breakage—crucial for library evolution.
Lessons from Language Evolution
Brian reflects on Lambda’s odyssey: discarded ideas like inner-class syntactic variants paved the way for invokedynamic’s elegance. This resilience, he posits, exemplifies evolving languages amid obvious-but-flawed intuitions.
Project Lambda’s resources—OpenJDK docs, JCP reviews—invite deeper exploration, with binary builds for experimentation.
Links:
[DevoxxFR2013] Les Cast Codeurs Podcast: Reflecting on Four Years of Java Community Insights
Lecturer
Emmanuel Bernard leads development on Hibernate and Quarkus at Red Hat, with expertise in ORM and data management. A Java Champion, he contributes to standards like JPA and Bean Validation. Vincent Massol acts as CTO at XWiki SAS, committing to the XWiki open-source project. He co-authored books on Maven and JUnit, and participates in Les Cast Codeurs podcast. Antonio Goncalves, Principal Software Engineer at Microsoft, founded the Paris Java User Group and authored books on Java EE. He engages in JCP expert groups for Java EE specifications. Guillaume Laforge advocates for Google Cloud Platform, previously managing Groovy. A Java Champion, he co-authored “Groovy in Action” and co-hosts Les Cast Codeurs. Arnaud Héritier manages software factories, committing to Apache Maven. He authored books on Maven and productivity, sharing at community events.
Abstract
This article evaluates the live recording of Les Cast Codeurs Podcast’s fourth anniversary at Devoxx France, hosted by Emmanuel Bernard, Vincent Massol, Antonio Goncalves, Guillaume Laforge, and Arnaud Héritier. It dissects discussions on Java ecosystem trends, conference experiences, and community dynamics. Framed as an informal yet insightful session, the analysis reviews topics like Java 8 features, build tools evolution, and event organization challenges. It assesses the podcast’s role in disseminating knowledge, implications for developer engagement, and reflections on technological shifts. Through anecdotes and audience interactions, it highlights the blend of humor, critique, and foresight that defines the podcast’s appeal in fostering a vibrant French Java community.
Origins and Evolution of Les Cast Codeurs
Les Cast Codeurs emerged from informal discussions among Java enthusiasts, evolving into a staple French-language podcast on Java and related technologies. Emmanuel recounts its inception four years prior, inspired by English counterparts like Java Posse. Initial episodes faced technical hurdles—recording via Skype with varying quality—but persistence yielded over 80 episodes by this milestone.
The format balances news, interviews, and debates, covering Java SE/EE advancements, tools like Maven and Gradle, and broader topics such as cloud computing. Vincent notes the shift from ad-hoc sessions to structured ones, incorporating listener feedback via tools like Google Forms for surveys. This anniversary episode, recorded live at Devoxx France, exemplifies community integration, with audience polls on attendance and preferences.
Growth metrics reveal listenership spikes around releases, averaging thousands per episode. Arnaud highlights international reach, with listeners in French-speaking regions and beyond, underscoring the podcast’s role in bridging linguistic gaps in tech discourse.
Navigating Java Ecosystem Trends and Challenges
Discussions delve into Java 8’s lambda expressions and streams, praised for enhancing code conciseness. Guillaume shares experiences with Groovy’s functional paradigms, drawing parallels to Java’s modernization. Critiques address Oracle’s stewardship post-Sun acquisition, with concerns over delayed releases and community involvement.
Build tools spark debate: Maven’s ubiquity contrasts with Gradle’s rising popularity for Android and flexibility. Antonio advocates for tool-agnostic approaches, while Emmanuel warns of migration costs. The panel concurs on the need for better dependency management, citing transitive conflicts as persistent issues.
Cloud and DevOps trends feature prominently, with reflections on PaaS like Cloud Foundry. Vincent emphasizes automation’s impact on deployment cycles, reducing manual interventions. Security vulnerabilities, like recent Java exploits, prompt calls for vigilant updates and sandboxing.
Community Engagement and Event Reflections
Devoxx France’s organization draws praise for inclusivity and speaker diversity. Arnaud recounts logistical feats—managing 1,000 attendees with volunteer support—highlighting French JUGs’ collaborative spirit. Comparisons to international Devoxx events note unique cultural flavors, like extended lunches fostering networking.
Audience polls reveal demographics: predominantly male, with calls for greater female participation. The panel encourages involvement in JUGs and conferences, citing benefits for skill-sharing and career growth. Humorous anecdotes, like Antonio’s “chouchou” moniker from keynote interactions, lighten the mood, reinforcing the podcast’s approachable style.
Reflections on past guests—industry leaders like James Gosling—underscore the platform’s prestige. Future plans include themed episodes on emerging tech like AI in Java.
Technological Shifts and Future Directions
The session probes Java’s relevance amid alternatives like Scala or Kotlin. Emmanuel defends Java’s ecosystem maturity, while Guillaume highlights Groovy’s interoperability. Discussions on open-source sustainability address funding models, with kudos to foundations like Apache.
Implications for education emphasize podcasts as accessible learning tools, supplementing formal training. The format’s conversational tone demystifies complex topics, aiding newcomers.
In conclusion, Les Cast Codeurs embodies community-driven knowledge dissemination, adapting to Java’s evolution while nurturing inclusivity. Its anniversary celebrates not just longevity but sustained impact on developer discourse.
Links:
[DevoxxFR2013] WTF – What’s The Fold?
Lecturer
Olivier Croisier operates as a freelance Java expert, trainer, and speaker through Moka Technologies. With over twelve years in the field, he assists clients in Java 8 migrations, advanced stack development, and revitalizing team enthusiasm for coding.
Abstract
Olivier Croisier elucidates the fold concept from functional programming, demonstrating its abstraction of iteration for enhanced code expressiveness. Using Java 8 streams and Haskell parallels, he dissects implementations, applications in mapping/filtering/reducing, and performance implications. The analysis positions fold as a versatile pattern surpassing traditional loops, integrable even in pre-Java 8 environments.
Origins and Essence: Fold as Iterative Abstraction
Croisier traces fold to functional languages like Haskell, where it generalizes accumulation over collections. Left fold (foldl) processes sequentially; right fold (foldr) enables laziness.
In essence, fold applies a binary operation cumulatively: start with accumulator, combine with each element.
Java analogy: external iterators (for-loops) versus internal (streams). Fold internalizes control, yielding concise, composable code.
Implementing Fold in Java: From Basics to Streams
Pre-Java 8, Croisier crafts a utility:
public static <T, R> R fold(Collection<T> coll, R init, BiFunction<R, T, R> f) {
R acc = init;
for (T e : coll) acc = f.apply(acc, e);
return acc;
}
Usage: sum integers—fold(list, 0, (a, b) -> a + b).
Java 8 streams natively provide reduce (fold alias):
int sum = list.stream().reduce(0, Integer::sum);
Parallel streams distribute: .parallelStream().reduce().
Croisier notes identity requirement for parallelism; non-associative operations risk inconsistencies.
Beyond Reduction: Mapping, Filtering, and Collection Building
Fold transcends summing; rebuild collections:
List<String> mapped = fold(list, new ArrayList<>(), (acc, e) -> { acc.add(transform(e)); return acc; });
Filter via conditional accumulation. This unifies operations—map/filter as specialized folds.
Haskell’s foldr constructs lists lazily, enabling infinite structures. Java’s eager evaluation limits but streams offer similar chaining.
Expressive Power and Performance Trade-offs
Croisier contrasts verbose loops with declarative folds, enhancing readability/maintainability. Encapsulate patterns in methods for reuse/optimization.
Performance: sequential folds match loops; parallel leverages multicore but incurs overhead (threading, combining).
JVM optimizations (invokedynamic for lambdas) potentially outperform anonymous classes. Croisier advocates testing under load.
Versus map-reduce: fold suits in-memory; Hadoop for distributed big data.
Integration Strategies and Broader Implications
Adopt incrementally: utility class for legacy code. Java 8+ embraces streams.
Croisier views fold as expressivity tool—not replacing conditionals but abstracting mechanics.
Implications: functional paradigms ease concurrency, prepare for multicore era. Fold’s versatility—from reductions to transformations—elevates code abstraction.
Links:
[DevoxxFR2013] FLATMAP ZAT SHIT: Monads Explained to Geeks
Lecturer
François Sarradin is a Java and lambda developer, serving as a technical capitalization manager. He contributes to the Brown Bag Lunch initiative, sharing expertise through presentations.
Abstract
François Sarradin’s session introduces monads in functional programming, using Scala and Java 8 examples to demystify their utility. He addresses handling errors, asynchrony, and technical concerns without cluttering business logic, employing monadic structures like Try and Future. The talk analyzes code transformations for cleaner, composable designs, highlighting monads’ role in aspect-oriented programming and drawing parallels to AOP frameworks.
The Problem: Technical Debt Obscuring Business Logic
Sarradin illustrates a common plight: initial clean code accumulates technical safeguards—null checks, try-catch blocks, synchronization—eroding readability and productivity. He proposes separating concerns: keep business logic pure, inject technical aspects via mechanisms akin to aspect-oriented programming (AOP).
Using AOP tools like AspectJ or Spring AOP declares cross-cutting concerns (e.g., logging, error handling) separately, leveraging compilers for coherence. This maintains original code structure while addressing realities like exceptions or async calls.
An example application in Scala computes total balance across bank accounts, initially straightforward but vulnerable. Technical intrusions (e.g., if-null, try-catch) bloat it, prompting a search for elegant solutions.
Introducing Monads: Error Handling with Try
To manage errors without pervasive checks, Sarradin introduces the Try monad in Scala: a container wrapping success (Success(value)) or failure (Failure(exception)). This allows chaining operations via flatMap and map, propagating errors implicitly.
Transforming the balance app: wrap account retrieval in Try, use for-comprehensions (sugaring flatMap/map) for composition. If any step fails, the whole computation fails gracefully, without explicit exception handling.
Code evolves from imperative checks to declarative chains:
val total = for {
account1 <- Try(getAccount(bank1))
account2 <- Try(getAccount(bank2))
balance1 <- Try(getBalance(account1))
balance2 <- Try(getBalance(account2))
} yield balance1 + balance2
This yields Try[Double], inspectable via isSuccess, get, or getOrElse. Monads here abstract error propagation, enhancing modularity.
Java 8’s Optional partially mirrors this but lacks full monadic power; Sarradin implements a custom Try for illustration, using abstract classes with Success/Failure subclasses.
Extending to Asynchrony: Futures for Non-Blocking Computations
Asynchrony poses similar issues: callbacks or blocking awaits disrupt flow. Scala’s Future monad encapsulates eventual values, enabling composition without blocking.
In the app, wrap async calls in Future: use flatMap to chain, ensuring non-blocking execution. For-comprehensions again simplify:
val totalFuture = for {
account1 <- Future(getAccountAsync(bank1))
account2 <- Future(getAccountAsync(bank2))
balance1 <- Future(getBalanceAsync(account1))
balance2 <- Future(getBalanceAsync(account2))
} yield balance1 + balance2
totalFuture completes asynchronously; callbacks via onComplete handle results. This maintains sequential appearance while parallelizing under the hood.
Sarradin contrasts with Java 8’s CompletableFuture, which offers thenApply/thenCompose for similar chaining, though less idiomatic without for-comprehensions.
Monads as a Unifying Abstraction: Synthesis and Implications
Monads generalize: a type M[A] with map (transform value) and flatMap (chain computations). They inject contexts (error, future) into pure functions, separating concerns.
In the app, combining Try and Future (via Scalaz’s EitherT or custom) handles both errors and asynchrony. This AOP-like injection leverages type systems for safety, contrasting annotation-based AOP.
Java 8 approximates with lambdas and CompletableFuture/Optional, but lacks Scala’s expressiveness. Custom implementations reveal monads’ essence: abstract class with map/flatMap, subclasses for Success/Failure.
Sarradin concludes monads enhance composability, reducing boilerplate for robust, maintainable code in functional paradigms.