Slides from my JAX London 2016 talk, discussing how the new features affect library design. Follows on from the Java SE 8 Best Practices talk - http://www.slideshare.net/scolebourne/java-se-8-best-practices-53975908
Introduction to functional idioms in Java 8, language-extending functional libraries and short overview of reasons for adoption of such programming style.
Examples and snippets available here: https://github.com/lbialy/functionaljava8
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
My presentation slides in KMS TechCon 2014, an internal technology event at KMS Technology Vietnam company.
"Java 8 is one of the most highly anticipated programming language updates in many years. Let me give you an introduction about its new features: Lambda expressions, Method references, Default Methods, Stream API, new JS Engine, new Date/Time API and more..."
Introduction to functional idioms in Java 8, language-extending functional libraries and short overview of reasons for adoption of such programming style.
Examples and snippets available here: https://github.com/lbialy/functionaljava8
Java 8 is one of the largest upgrades to the popular language and framework in over a decade. This talk will detail several new key features of Java 8 that can help make programs easier to read, write, and maintain. Java 8 comes with many features, especially related to collection libraries. We will cover such new features as Lambda Expressions, the Stream API, enhanced interfaces, and more.
My presentation slides in KMS TechCon 2014, an internal technology event at KMS Technology Vietnam company.
"Java 8 is one of the most highly anticipated programming language updates in many years. Let me give you an introduction about its new features: Lambda expressions, Method references, Default Methods, Stream API, new JS Engine, new Date/Time API and more..."
Presentation on the new features introduced in JDK 8, presented on the 26.02.2013 in Sofia University in front of students and members of the Bulgarian java user group.
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)DevelopIntelligence
Kelby Zorgdrager from DevelopIntelligence explains the differences between the variations of Java and what's new in Java 7.
If you need help with Java training DevelopIntelligence and provide on-site training within two weeks. Customized and affordable for any organization.
www.denizoguz.com-For an in company JDK 7 orientation I have prepared a presentation which summaries new features of JDK 7. I would like to make it public for everyone who needs it.
Presentation from Riga Dev Day talking about Lambda expressions and the Stream API in JDK8. This session, as the title suggests, goes beyond the basics and discusses some of the different ways you need to think to use a functional style of programming in Java.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
A code review is basically a technical discussion which should lead to improvements in the code and/or sharing
knowledge in a team. As with any conversation, it should have substance and form.
What’s involved in a good code review? What kind of problems do we want to spot and address? Trisha Gee will talk
about things a reviewer may consider when looking at changes: what potential issues to look for; why certain
patterns may be harmful; and, of course, what NOT to look at.
But when it comes to commenting on someone’s work, it may be hard to find the right words to convey a useful message
without offending the authors - after all, this is something that they worked hard on. Maria Khalusova will share
some observations, thoughts and practical tricks on how to give and receive feedback without turning a code review
into a battlefield.
Presentation made by [Michael Suriano, NBBJ and Tracy Anne Perry, NBBJ] at the IFLA Library Buildings and Equipment Satellite Meeting, Illinois Institute of Technology, Chicago, Aug.10-11, 2016.
Presentation on the new features introduced in JDK 8, presented on the 26.02.2013 in Sofia University in front of students and members of the Bulgarian java user group.
Whats New in Java 5, 6, & 7 (Webinar Presentation - June 2013)DevelopIntelligence
Kelby Zorgdrager from DevelopIntelligence explains the differences between the variations of Java and what's new in Java 7.
If you need help with Java training DevelopIntelligence and provide on-site training within two weeks. Customized and affordable for any organization.
www.denizoguz.com-For an in company JDK 7 orientation I have prepared a presentation which summaries new features of JDK 7. I would like to make it public for everyone who needs it.
Presentation from Riga Dev Day talking about Lambda expressions and the Stream API in JDK8. This session, as the title suggests, goes beyond the basics and discusses some of the different ways you need to think to use a functional style of programming in Java.
Java 8 came out early last year and Java 7 is now, at the end of life, making Java 8 the only Oracle supported option. However, since developers value stability over trendiness, many of us are still working with Java 7, or even 6. Let’s look at some features of Java 8, and provide some arguments to persuade your code to upgrade with best practices.
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
A code review is basically a technical discussion which should lead to improvements in the code and/or sharing
knowledge in a team. As with any conversation, it should have substance and form.
What’s involved in a good code review? What kind of problems do we want to spot and address? Trisha Gee will talk
about things a reviewer may consider when looking at changes: what potential issues to look for; why certain
patterns may be harmful; and, of course, what NOT to look at.
But when it comes to commenting on someone’s work, it may be hard to find the right words to convey a useful message
without offending the authors - after all, this is something that they worked hard on. Maria Khalusova will share
some observations, thoughts and practical tricks on how to give and receive feedback without turning a code review
into a battlefield.
Presentation made by [Michael Suriano, NBBJ and Tracy Anne Perry, NBBJ] at the IFLA Library Buildings and Equipment Satellite Meeting, Illinois Institute of Technology, Chicago, Aug.10-11, 2016.
Two years ago, we introduced Spock tests into the MongoDB Java driver. The decision could be considered controversial – the project used no external dependencies in production code, and was 100% Java. But there was a back door… with Gradle as the build system, there was a tiny excuse to use Groovy in the project, provided it wasn’t in the production code. That’s all the excuse we needed to start using Spock for unit and, later, integration tests.
Groovy has a lot of advantages as a testing language, and with Spock’s mocking, stubbing, and data driven testing features, it might seem as if this is the perfect way to write tests. In this session, Trisha will cover some of the features that make Spock (and Groovy) compelling for writing tests. But in the interests of fairness, she’ll also discuss some of the downsides, and the times when Java was chosen instead.
North Carolina's Fearrington Village is home to many artists. Dr. Forrest Greenslade lives and creates there. He exhibits his sculpture and paintings in the Forrest Dweller Sculpture Garden and Gallery. Take a pictorial tour.
Lecture presented by Fe Angela M. Verzosa at PAARL’s One-Day Seminar on the theme "Revitalized Library Networking: PAARLNet at the Frontline" (Epifanio de los Santos Auditorium, The National Library, T.M. Kalaw, Manila, 25 November 2010)
Though revolutionary in many ways, digital photography is essentially electronically implemented film photography. By contrast, computational photography exploits plentiful low-cost computing and memory, new kinds of digitally enabled sensors, optics, probes, smart lighting, and communication to capture information far beyond just a simple set of pixels. It promises a richer, even a multilayered, visual experience that may include depth, fused photo-video representations, or multispectral imagery. Professor Raskar will discuss and demonstrate advances he is working on in the areas of generalized optics, sensors, illumination methods, processing, and display, and describe how computational photography will enable us to create images that break from traditional constraints to retain more fully our fondest and most important memories, to keep personalized records of our lives, and to extend both the archival and the artistic possibilities of photography.
An overview of software engineering project (MSc Thesis) to objectively evaluate the benefits and drawbacks of using Model-Driven Engineering tools on Eclipse Modelling Framework (EMF) such as Epsilon and Xtext to implement a compiler for a sufficiently complex intermediate language. The results seem promising.
For more imnformation, please see this blog post:
http://modeling-languages.com/re-implementing-apache-thrift-with-mde/
These are the slides to the webinar about Custom Pregel algorithms in ArangoDB https://youtu.be/DWJ-nWUxsO8. It provides a brief introduction to the capabilities and use cases for Pregel.
Design and Implementation of the Security Graph LanguageAsankhaya Sharma
Today software is built in fundamentally different
ways from how it was a decade ago. It is increasingly common
for applications to be assembled out of open-source components,
resulting in the use of large amounts of third-party code. This
third-party code is a means for vulnerabilities to make their
way downstream into applications. Recent vulnerabilities such
as Heartbleed, FREAK SSL/TLS, GHOST, and the Equifax data
breach (due to a flaw in Apache Struts) were ultimately caused
by third-party components. We argue that an automated way to
audit the open-source ecosystem, catalog existing vulnerabilities,
and discover new flaws is essential to using open-source safely.
To this end, we describe the Security Graph Language (SGL), a
domain-specific language for analysing graph-structured datasets
of open-source code and cataloguing vulnerabilities. SGL allows
users to express complex queries on relations between libraries
and vulnerabilities in the style of a program analysis language.
SGL queries double as an executable representation for vulnerabilities, allowing vulnerabilities to be automatically checked
against a database and deduplicated using a canonical representation. We outline a novel optimisation for SGL queries based on
regular path query containment, improving query performance up to 3 orders of magnitude. We also demonstrate the
effectiveness of SGL in practice to find zero-day vulnerabilities
by identifying sever
Unifying Frontend and Backend Development with Scala - ScalaCon 2021Taro L. Saito
Scala can be used for developing both frontend (Scala.js) and backend (Scala JVM) applications. A missing piece has been bridging these two worlds using Scala. We built Airframe RPC, a framework that uses Scala traits as a unified RPC interface between servers and clients. With Airframe RPC, you can build HTTP/1 (Finagle) and HTTP/2 (gRPC) services just by defining Scala traits and case classes. It simplifies web application design as you only need to care about Scala interfaces without using existing web standards like REST, ProtocolBuffers, OpenAPI, etc. Scala.js support of Airframe also enables building interactive Web applications that can dynamically render DOM elements while talking with Scala-based RPC servers. With Airframe RPC, the value of Scala developers will be much higher both for frontend and backend areas.
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
Dart is a new language for the web, enabling you to write JavaScript on a secure and manageable way. No need to worry about "JavaScript: The bad parts".
This presentation concentrates on the developer experience converting from the Java based GWT to Dart.
Explores and discusses benefits of functional programming in Java and how to program in a functional style. Watch Venkat Subramaniam's talk at https://youtu.be/Ee5t_EGjv0A if you would like to learn more.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
1. Java SE 8 Library Design
Using the new features well
Stephen Colebourne
Engineering Lead, OpenGamma
October 2016
2. Stephen Colebourne
● Java Champion, regular conference speaker
● Best known for date & time - Joda-Time and JSR-310
● More Joda projects - http://www.joda.org
● Major contributions in Apache Commons
● Blog - http://blog.joda.org
● Worked at OpenGamma for 6 years
3. Strata, from OpenGamma
● Open Source market risk library
● Valuation and risk calcs for finance
○ interest rate swap, FRA, CDS
● Great example of Java SE 8 coding style
http://strata.opengamma.io/
9. Lambdas
● Block of code
○ like an anonymous inner class
● Always assigned to a Functional Interface
○ an interface with one abstract method
○ Runnable, Callable, Comparator
● Uses target typing
○ context determines type of the lambda
10. // Java 7
List<Person> people = loadPeople();
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
Lambdas
public interface Comparator<T> {
int compare(T obj1, T obj2);
}
// Java 7
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
11. // Java 7
List<Person> people = loadPeople();
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
Lambdas
public interface Comparator<T> {
int compare(T obj1, T obj2);
}
// Java 7
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
12. // Java 7
List<Person> people = loadPeople();
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.name.compareTo(p2.name);
}
});
Lambdas
public interface Comparator<T> {
int compare(T obj1, T obj2);
}
// Java 8
people.sort((p1, p2) -> p1.name.compareTo(p2.name));
13. Top tips for Lambdas
● Use lambdas wherever appropriate
● Mostly, they just work
● Sometimes, the compiler needs a hint
○ use local variable
○ add the type to the lambda parameter
16. Streams
● Many loops have a similar "shape"
● Repetitive design patterns
● Stream library provides a way to abstract this
● Lambdas used to pass the interesting bits
17. Streams
List<Trade> trades = loadTrades();
List<Money> valued = new ArrayList<>();
for (Trade t : trades) {
if (t.isActive()) {
Money pv = t.presentValue();
valued.add(pv);
}
}
18. Streams
List<Trade> trades = loadTrades();
List<Money> valued = new ArrayList<>();
for (Trade t : trades) {
if (t.isActive()) {
Money pv = t.presentValue();
valued.add(pv);
}
}
20. Streams
● New stream() method on Collection
● Sequence of operations on underlying data
● Logic passed in using a lambda
○ filter() to retain/remove
○ map() to change
○ reduce() to summarise
○ sorted() to sort using a comparator
24. Exceptions in Streams
● For-each loop is a language feature
● Streams are implemented using regular methods
● Big difference in stack traces
25. Exceptions in Streams
java.lang.IllegalArgumentException: Oops
at com.opengamma.strata.calc.DefaultCalculationRunner.lambda$2(DefaultCalculationRunner.java:98)
at java.util.stream.ReferencePipeline$11$1.accept(ReferencePipeline.java:372)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.opengamma.strata.calc.DefaultCalculationRunner.calculate(DefaultCalculationRunner.java:100)
at com.opengamma.strata.calc.DefaultCalculationRunner.lambda$0(DefaultCalculationRunner.java:86)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.opengamma.strata.calc.DefaultCalculationRunner.calculate(DefaultCalculationRunner.java:87)
at com.opengamma.strata.calc.DefaultCalculationRunnerTest.calculate(DefaultCalculationRunnerTest.java:49)
Stack trace of
inner stream
Stack trace of
outer stream
26. Exceptions in Streams
java.lang.IllegalArgumentException: Oops
at com.opengamma.strata.calc.DefaultCalculationRunner.calculate(DefaultCalculationRunner.java:102)
at com.opengamma.strata.calc.DefaultCalculationRunner.calculate(DefaultCalculationRunner.java:87)
at com.opengamma.strata.calc.DefaultCalculationRunnerTest.calculate(DefaultCalculationRunnerTest.java:49)
Stack trace of
for-each loop
27. Top tips for streams
● Stream not always more readable than loop
● Stream exceptions can be much worse
● My advice:
○ use streams for small, localized, pieces of logic
○ be cautious using streams for large scale logic
● Strata uses for-each loops at top level
○ solely for shorter stack traces
29. Design with Lambdas
● Lambda is converted to a functional interface
● Normal interface with one abstract method
● Java SE 8 adds many new functional interfaces
○ Function<T, R>
○ Predicate<T>
○ Supplier<T>
○ Consumer<T>
○ see java.util.function package
● Primitive versions only for long, int, double
30. Functional interfaces
● Learn the standard functional interfaces
● Only create new ones if adding additional value
○ lots of parameters
○ mix of primitive and object parameters
○ feature really needs a good name or Javadoc
31. Functional interface example
// API functional interface
@FunctionalInterface
public interface Perturbation {
public abstract double perturb(int index, double value);
}
// API method that can be used by a lambda
public Curve perturbed(Perturbation perturbation) { … }
// caller code
curve = curve.perturbed((i, v) -> v + 1e-4);
32. Functional interface example
// API functional interface
@FunctionalInterface
public interface Perturbation {
public abstract double perturb(int index, double value);
}
// API method that can be used by a lambda
public Curve perturbed(Perturbation perturbation) { … }
// caller code
curve = curve.perturbed((i, v) -> v + 1e-4);
Name has meaning
Method signature is complex
33. Time-series example
● A time-series stores changes to a value over time
● Date-based one like Map<LocalDate, Double>
● What if you want to change the values?
34. Time-series example
// API method that can be used by a lambda
public LocalDateDoubleTimeSeries
mapValues(DoubleUnaryOperator mapper){ … }
// caller code
ts = ts.mapValues(v -> v * 2);
35. Time-series example
// API method that can be used by a lambda
public LocalDateDoubleTimeSeries
mapValues(DoubleUnaryOperator mapper){ … }
// caller code
ts = ts.mapValues(v -> v * 2);
Multiplication - no need for
multipliedBy(double)
on the API
36. Time-series example
// API method that can be used by a lambda
public LocalDateDoubleTimeSeries
mapValues(DoubleUnaryOperator mapper){ … }
// caller code
ts = ts.mapValues(v -> v * 2);
ts = ts.mapValues(v -> v / 4);
Multiplication - no need for
multipliedBy(double)
on the API
Division - no need for
dividedBy(double)
on the API
39. Abstraction
● Two or more classes with the same methods
● Abstract using an interface?
● Lambdas provide an alternative
● Consider an example with static methods
○ no way to abstract that with interfaces...
40. Abstraction
// standard API producing results
public static Money pv(FraTrade trade, Market md) { … }
public static Sens pv01(FraTrade trade, Market md) { … }
public static Double par(FraTrade trade, Market md) { … }
41. Abstraction
// standard API producing results
public static Money pv(FraTrade trade, Market md) { … }
public static Sens pv01(FraTrade trade, Market md) { … }
public static Double par(FraTrade trade, Market md) { … }
// functional interface matching all three methods
interface Calc<T> {
public abstract T invoke(FraTrade trade, Market market);
}
42. Abstraction
// create abstraction to access method by "measure" key
Map<Measure, Calc> CALCS = ImmutableMap.builder()
.put(Measures.PRESENT_VALUE, FraCalcs::pv)
.put(Measures.PV01, FraCalcs::pv01)
.put(Measures.PAR_RATE, FraCalcs:: par)
.build();
// can now invoke using measure
return CALCS.get(measure).invoke(trade, market);
43. Abstraction
● Class being abstracted was not changed
● Provides way to abstract over code you do not own
● Less need for reflection
46. Multi-threaded
● JDK provides many tools for concurrency
● Parallel streams makes it even easier
● But parallel code is not simple to get right
47. Thread problems
● What if trade modified by some other piece of code?
● Check-then-act bug
List<Trade> trades = loadTrades();
List<Money> valued =
trades.stream()
.filter(t -> t.isActive())
.map(t -> presentValue(t))
.collect(Collectors.toList());
Check
then Act
48. Immutable
● Threading bugs due to shared mutable state
● One solution is to use immutable beans
● No possibility of check-then-act type bug
49. Immutable beans
● Class should be final
○ no subclasses
● Fields must be final
○ needed for Java Memory Model
● Field types should be immutable
○ eg. don't use java.util.Date
● Factory methods and Builders instead of constructors
50. Immutable beans
● IDEs help you write mutable beans
● Need better tooling for immutable beans
○ AutoValue
○ Immutables.org
○ Joda-Beans
● Strata uses Joda-Beans
http://www.joda.org/joda-beans
51. Joda-Beans
@BeanDefinition
public final TradeInfo implements ImmutableBean {
/** The trade identifier. */
@PropertyDefinition(validate = "notNull")
private final StandardId tradeId;
/** The trade date. */
@PropertyDefinition(validate = "notNull")
private final LocalDate tradeDate;
}
52. Joda-Beans
● Source code generated for
○ getters
○ builder
○ equals/hashCode/toString
○ properties - like C#
● Can add your own code to the class and still regenerate
● Built in XML, JSON and Binary serialization
53. Immutable beans
● Most systems better using immutability everywhere
● Java SE 8 parallelStream() pushes at this
● Threading issues mostly eliminated
● No class hierarchies, use interfaces
55. Use interfaces
● Concrete classes with no hierarchies
● Interfaces provide the hierarchy
● Methods on interfaces make this practical
● All implementations of interface should be immutable
○ "Implementations must be immutable and thread-safe beans."
● Strata uses immutable beans everywhere
58. Interfaces
● Two changes to interfaces
● Default methods
○ normal method, but on an interface
○ cannot default equals/hashCode/toString
● Static methods
○ normal static method, but on an interface
59. Coding Style
● Use modifiers in interfaces
● Much clearer now there are different types of method
● Prepares for private methods in Java SE 9
public interface Foo {
public static of(String id) { … }
public abstract isEmpty();
public default isNotEmpty() { … }
}
60. Interfaces
● Methods on interfaces changes design
● Interfaces are part of macro-design
○ lambdas and streams affect micro-design
● Strata uses default and static methods liberally
61. Holiday Calendar
● Strata interface to specify which days are holidays
public interface HolidayCalendar {
// a normal abstract interface method
public abstract isHoliday(LocalDate date);
…
}
62. Holiday Calendar
● Default methods make the interface more useful
public interface HolidayCalendar {
public abstract isHoliday(LocalDate date);
// check if date is a business day
public default isBusinessDay(LocalDate date) {
return !isHoliday(date);
}
}
63. Holiday Calendar
● Default methods make the interface more useful
public interface HolidayCalendar {
public abstract isHoliday(LocalDate date);
// find the next business day
public default next(LocalDate date) {
LocalDate nextDay = date.plusDays(1);
return isHoliday(nextDay) ? next(nextDay) : nextDay;
}
}
64. Holiday Calendar
● Static methods avoid HolidayCalendarFactory
public interface HolidayCalendar {
// find holiday calendar by identifier such as DKCO
public static of(String id) {
// lookup calendar
}
}
65. Holiday Calendar
● Interface used just as would be expected
// find holiday calendar by identifier such as DKCO
HolidayCalendar cal = HolidayCalendar.of("DKCO");
// use calendar to select the trade start date
LocalDate startDate = cal.next(tradeDate);
66. Interfaces
● Interface now acts as abstract class
○ Only need abstract class if need abstracted state
○ but abstracted state is generally a bad idea
● Interface can now acts as a factory
○ Not suitable for all factory use cases*
* In Strata, holiday calendars are not really fixed at startup, but it made a good example for this talk!
67. Package-scoped implementation
● Can the interface be the only public API?
● Can the implementation class be package-scoped?
● Strata uses this pattern a lot
70. Optional and null
● New class Optional added to Java 8
● Opinions are polarized
○ some think it is the saviour of the universe
○ others think it is useless
● Used pragmatically, can be very useful
71. Optional and null
● Simple concept - two states
○ present, with a value - Optional.of(foo)
○ empty - Optional.empty()
72. Optional and null
● Standard code using null
// library, returns null if not found
public Foo getValue(String key) { … }
// application code must remember to check for null
Foo foo = getValue(key);
if (foo == null) {
foo = Foo.DEFAULT; // or throw an exception
}
73. Optional and null
● Standard code using Optional
// library, returns Optional if not found
public Optional<Foo> findValue(String key) { … }
// application code
Foo foo = findValue(key).orElse(Foo.DEFAULT);
// or
Foo foo = findValue(key).orElseThrow( … );
74. Optional and null
● Important that a variable of type Optional is never null
● Prefer methods like map() and orElse()
● Minimise use of isPresent()
75. Optional
● Strata often uses set of 3-methods
public abstract Optional<T> findValue(DataId<T> id);
public default boolean containsValue(DataId<T> id) {
return findValue(id).isPresent();
}
public default T getValue(DataId<T> id) {
return findValue(id).orElseThrow(
() -> new MarketDataException());
}
76. Optional
● Optional is a class
● Some memory/performance cost to using it
● Not serializable
● Not ideal to be an instance variable
● JDK authors added it for return types
● Use in parameters often annoying for callers
● Use as return type gets best value from concept
http://blog.joda.org/2015/08/java-se-8-optional-pragmatic-approach.html
77. Optional in Strata
● Strata has no exposed nulls
● No part of the API will return null
● Optional used when something is optional
● Pragmatically, null is used within classes
80. Java SE 8 version
● Use Java SE 8 update 40 or later
○ preferably use the latest available
● Earlier versions have annoying lambda/javac issues
81. Internal JDK packages
● Java SE 9 will remove access to some JDK packages
○ sun.*
○ com.sun.*
○ com.oracle.*
● Now is the time to prepare for this
○ Avoid sun.misc.Unsafe
○ Stick to the standard JDK API
82. Parameters
● Java SE 8 can reflect on parameter names
● Avoids need for additional libraries like paranamer
● Not enabled by default, must choose to include data
83. Checked exceptions
● Checked exceptions can be made to disappear
● Helper methods can convert to runtime exceptions
Unchecked.wrap(() -> {
// any code that might throw a checked exception
// converted to a runtime exception
});
85. Summary
● Lots of good stuff in Java SE 8
● Design and coding standards change
● Lots more potential to abstract, but don't over-use
● Methods on interfaces add a lot of power
86. Key Strata design features
● Immutable data objects, using Joda-Beans
● Static methods on interfaces, package-scope impls
● Make use of new abstractions
● Beware stack traces with streams
● Pragmatic use of Optional, null never returned from API
87. Work in Finance?
● Take a look at OpenGamma Strata
○ developed from the ground up in Java 8
○ lots of good Java 8 techniques and utilities
● High quality library for market risk
○ day counts, schedules, holidays, indices
○ models and pricing for swaps, FRAs, swaptions, FX, futures…
○ open source and stable release v1.1
http://strata.opengamma.io/