Guava - open-source библиотека, разработанная в основном инженерами компании Google, в которой есть множество полезных утилит для написания эффективного и красивого кода. В Guava решено множество типичных задач, которые часто возникают при работе с примитивами, строками, коллекциями, параллельными вычислениями, кэшированием данных и многим другим. В докладе поговорим о возможностях, которые предоставляет Guava, рассмотрим примеры использования утилит библиотеки.
Solit 2013, JVM изнутри: оптимизация и профилирование, Слисенко Константинsolit
Слисенко Константин, Минск. Компания JazzTeam, Senior Software Engineer (R&D), Java/Agile Coach
«Разработка приложений в облаке на примере Amazon Web Services». Development секция. Для разработчиков.
«JVM изнутри: оптимизация и профилирование». Development секция. Для разработчиков.
The document describes a presentation on writing a TableGen backend. It introduces TableGen as a domain-specific language originated from LLVM to describe instruction tables and other target-specific data in a declarative way. TableGen backends generate target code from TableGen input. The presentation discusses using TableGen records to represent data, differences between OOP and TableGen, TableGen data types, and provides an example of how TableGen is used in LLVM backends to generate code from the table description files for targets.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
[부산] 로봇 운영체제 ROS 세미나 / 2015.7.8
로봇 소프트웨어 개발을 위한 소프트웨어 프레임워크인 로봇 운영체제 ROS 대한 초심자 대상 기술 세미나
[이야기 하나!]
1. 강의제목 : 로봇 운영체제 ROS 개론
2. 강좌내용
(1) 로봇 소프트웨어 플랫폼의 필요성
(2) 로봇 운영체제 ROS 소개
(3) 로봇 운영체제 ROS 개념
(4) 로봇 운영체제 ROS 특징과 활용
[이야기 둘!!]
1. 강의제목 : ROS를 활용한 SLAM과 내비게이션
2. 강좌내용
(1) ROS를 활용한 모바일 로봇의 위치추정과 맵핑 (SLAM)
(2) ROS를 활용한 모바일 로봇의 내비게이션 (Navigation)
[이야기 셋!!!]
1. 강의제목 : 로봇 암 모델링과 Moveit! 사용법
2. 강좌내용
(1) 3D가식화 툴 RViz 및 시뮬레이터 Gazibo를 위한 실제 로봇암의 모델링
(2) 모션 플래닝 MoveIt! 사용법
The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.
This document discusses conditional statements and switch statements in C#. It explains the syntax and usage of if, else, else if, and ternary conditional statements. It also covers the syntax and purpose of switch statements, including the break and default keywords. Code examples are provided to demonstrate how to use if/else, else if, ternary operators, and switch statements to conditionally execute blocks of code based on simple logic checks and comparisons of variables.
The document provides an overview of C++17's std::filesystem library. It introduces the Path class for representing file system paths, the DirectoryEntry class for modeling directory entries, and DirectoryIterator for iterating over directories. It also summarizes key support functions for querying and modifying files and directories, handling permissions, and catching errors and exceptions. Examples are provided demonstrating how to get a file size, iterate over a directory, and monitor a directory for changes using std::filesystem.
Solit 2013, JVM изнутри: оптимизация и профилирование, Слисенко Константинsolit
Слисенко Константин, Минск. Компания JazzTeam, Senior Software Engineer (R&D), Java/Agile Coach
«Разработка приложений в облаке на примере Amazon Web Services». Development секция. Для разработчиков.
«JVM изнутри: оптимизация и профилирование». Development секция. Для разработчиков.
The document describes a presentation on writing a TableGen backend. It introduces TableGen as a domain-specific language originated from LLVM to describe instruction tables and other target-specific data in a declarative way. TableGen backends generate target code from TableGen input. The presentation discusses using TableGen records to represent data, differences between OOP and TableGen, TableGen data types, and provides an example of how TableGen is used in LLVM backends to generate code from the table description files for targets.
download for better quality - Learn about the sequence and traverse functions
through the work of Runar Bjarnason and Paul Chiusano, authors of Functional Programming in Scala https://www.manning.com/books/functional-programming-in-scala
[부산] 로봇 운영체제 ROS 세미나 / 2015.7.8
로봇 소프트웨어 개발을 위한 소프트웨어 프레임워크인 로봇 운영체제 ROS 대한 초심자 대상 기술 세미나
[이야기 하나!]
1. 강의제목 : 로봇 운영체제 ROS 개론
2. 강좌내용
(1) 로봇 소프트웨어 플랫폼의 필요성
(2) 로봇 운영체제 ROS 소개
(3) 로봇 운영체제 ROS 개념
(4) 로봇 운영체제 ROS 특징과 활용
[이야기 둘!!]
1. 강의제목 : ROS를 활용한 SLAM과 내비게이션
2. 강좌내용
(1) ROS를 활용한 모바일 로봇의 위치추정과 맵핑 (SLAM)
(2) ROS를 활용한 모바일 로봇의 내비게이션 (Navigation)
[이야기 셋!!!]
1. 강의제목 : 로봇 암 모델링과 Moveit! 사용법
2. 강좌내용
(1) 3D가식화 툴 RViz 및 시뮬레이터 Gazibo를 위한 실제 로봇암의 모델링
(2) 모션 플래닝 MoveIt! 사용법
The document discusses object-oriented programming (OOP) and functional programming (FP). It argues that OOP and FP are not opposites and can be effectively combined. It addresses common myths about FP, such as that it is new, hard, or only suitable for mathematical problems. The document also compares how OOP and FP approach concepts like decomposition, composition, error handling, and mutability/referential transparency. While both approaches have merits, the document concludes there is no single best approach and the choice depends on the problem and programmer preferences.
This document discusses conditional statements and switch statements in C#. It explains the syntax and usage of if, else, else if, and ternary conditional statements. It also covers the syntax and purpose of switch statements, including the break and default keywords. Code examples are provided to demonstrate how to use if/else, else if, ternary operators, and switch statements to conditionally execute blocks of code based on simple logic checks and comparisons of variables.
The document provides an overview of C++17's std::filesystem library. It introduces the Path class for representing file system paths, the DirectoryEntry class for modeling directory entries, and DirectoryIterator for iterating over directories. It also summarizes key support functions for querying and modifying files and directories, handling permissions, and catching errors and exceptions. Examples are provided demonstrating how to get a file size, iterate over a directory, and monitor a directory for changes using std::filesystem.
This document provides examples of refactoring Java code to use Guava libraries and utilities. It shows code snippets before and after refactoring to use Guava's Objects, Preconditions, Collections, Splitter, Joiner, Ranges and other utilities to clean up code and make it more readable and robust. Refactoring includes using Guava to validate arguments, create immutable collections, handle nulls safely, join/split strings, and represent ranges.
Полной автоматизацией процесса сборки приложения уже никого не удивишь. Не в последнюю очередь благодаря Maven – системе управления жизненным циклом проекта. Однако проекты растут очень быстро: увеличивается количество модулей, тестов, зависимостей, используемых плагинов. И всего лишь за год легковесный проект, на сборку которого уходило 5 минут, превращается в монстра, который пожирает время разработчиков 30-минутной сборкой. Чтобы справится с этой проблемой разработчикам приходится постоянно чистить свой код и бороться со скоростью выполнения тестов. Это верное решение, но не следует забывать о том, что и сам процесс сборки можно улучшить. В этом докладе будет рассмотрено, как при помощи простых и нехитрых шагов можно оптимизировать работу с зависимостями и обогатить скрипты сборки полезными плагинами. Также будут обсуждаться тонкости конфигурации основных плагинов и особенности работы с командной строкой, которые появились в последней версии Maven.
About Spring in pictures.
Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.
Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Why should we know about Spring internals? It works! So use it and enjoy! However, as always, in order to use Spring in most efficient way, you must know, what is under the fork. Only in case you really understand its internals you will be able to use all power of Spring. You will be able to customize this framework according to challenges of your project, to achieve best performance and solve any problem without applying to Spring-support center. ;) Here are several topics about Spring internals, which will be covered during this session (with examples for each one): What is Spring impact on the performance of your application? What are the phases of Spring lifecycle? What is ApplicationContext structure? “You can’t do it with Spring!” – or maybe you can?
The document summarizes a presentation about the Phoenix framework. It includes:
1. An introduction from Chris McCord, inventor of Phoenix, about how Phoenix is similar to and different from Ruby on Rails.
2. Sections discussing how Phoenix draws inspiration from Rails but is optimized for concurrency using the Erlang VM and functional programming principles like immutability.
3. Advice that incremental adoption of Phoenix for new features or rewrites is better than sudden wholesale changes, to minimize disruption for developers and users.
This is a presentation given on October 24 by Michael Uzquiano of Cloud CMS (http://www.cloudcms.com) at the MongoDB Boston conference.
In this presentation, we cover Hazelcast - an in-memory data grid that provides distributed object persistence across multiple nodes in a cluster. When backed by MongoDB, objects are naturally written to Mongo by Hazelcast. The integration points are clean and easy to implement.
We cover a few simple cases along with code samples to provide the MongoDB community with some ideas of how to integrate Hazelcast into their own MongoDB Java applications.
«Бутылочное горлышко многопоточных программ – кто виноват, и что делать. Мастер-класс.»
BitByte: 20 апреля 2013, Санкт-Петербург
http://bitbyte.itmozg.ru/
When you work in a small collocated team many engineering practices and approaches are relatively easy to use and adapt. In large project with many teams working on the same product this task is not so simple. I want to share experience report in implementing Code Review practice in big product development team (more than 150 people, 10+ feature teams). In this talk we will review what approaches works in such setup and what don’t work, what tools and additional practices are needed to support Code Review and make it more effective, what difficulties and blockers will you probably see in the real life cases, what useful metrics could be produced by this practice.
In this webinar we will compare the complexities involved in Terracotta with the code/configuration changes to migrate to Hazelcast. You will learn about important features of Hazelcast such as IMDG capabilities, off-heap data storage, distributed collections, etc. and the feature-rich product portfolio of Hazelcast. We will cover how Hazelcast can scale up and out dynamically and without downtime against the static configuration of Terracotta. Expect to leave the webinar being more educated about Hazelcast in terms of architecture, important features and best practices.
We’ll cover these topics:
- Hazelcast architecture and features
- Terracotta distributed architecture
- Scale – Vertical + Horizontal = Showcase no downtime feature in Hazelcast
- BigMemory vs. HDC
- Ease of installation – two jars against multiple jars
- Config and Code changes – cache vs. maps, off-heap vs. HDC
- Portability of Client APIs – IMap, IQueue, Topics, etc.
- Added functionalities – Showcase IExecutorService, EntryProcessors, Multimap, etc.
- DSO – Showcase EntryProcessors taking place of DSO
- Live Q&A
Presenter:
Rahul Gupta, Senior Solutions Architect
Rahul is a technology-driven professional with 12+ years of experience in building and architecting highly scalable and concurrent, low latency business critical distributed infrastructure. His expertise lies in Big Data and Real Time Analytics space where he specializes in big data governing technologies and Enterprise Architecture. Rahul is an expert in working with decision makers across different business verticals within an organization and guiding them in right decision making through in-depth technical understanding, analysis and evaluation procedures to bring home critical deals with high business values.
Of course Java 8 is all about lambda expressions and this new wonderful Stream API. Now the question is, what's left in Java 8, once we've removed everything : lambdas, streams, collectors, java FX and Nashorn ? This presentation gathered all these new diamonds, scattered all around the JDK, brand new classes, and new methods in existing classes.
The document discusses new features in Java related to numbers and strings. It describes new methods like max(), min(), and sum() that are available on number wrapper classes. It also discusses improved ways to concatenate strings in Java 8 using StringJoiner and the join() method on the String class. The document notes how these features can make code more readable by allowing method references.
Gamification in outsourcing company: experience report.Mikalai Alimenkou
Most of us used to hear word gamification only for end user engagement into product usage. Some of us know about usage of similar approaches in product development teams to improve and tune development process. But almost nobody believes that gamification is possible in the context of outsourcing companies and teams. This talk is experience report of gamification usage on very large project with detailed reusable framework demonstration. If you want to bring some fun and really engage your team, then this talk is for you.
This document discusses Java 8 features including Optional, lambdas, and Stream API. It provides advice on properly using Optional to avoid null checks, keeping lambda expressions simple, and only using streams for functional-style operations without side effects. The document recommends using method references when possible and external libraries like jOOL and StreamEx that extend the stream functionality. It concludes by providing contact information for the authors to ask additional questions.
Developers want to make very few errors in their code and to spot them as early as possible: with the help of unit tests, or earlier, during compilation, or best of all, immediately after they typed something wrong in their IDE. This is what static code analyzers are for. Some of them are built-in, others need to be run separately, some check just about any code, the others require it to be annotated first, and there are tools that are a little bit of all. Do the ends justify the means? Is it even worth trying? What kind of errors can be spotted by static code analysis? How sure can we be if what an analyzer gives us is a real error or a false positive? This talk hopefully helps you answer these questions.
This document provides examples of refactoring Java code to use Guava libraries and utilities. It shows code snippets before and after refactoring to use Guava's Objects, Preconditions, Collections, Splitter, Joiner, Ranges and other utilities to clean up code and make it more readable and robust. Refactoring includes using Guava to validate arguments, create immutable collections, handle nulls safely, join/split strings, and represent ranges.
Полной автоматизацией процесса сборки приложения уже никого не удивишь. Не в последнюю очередь благодаря Maven – системе управления жизненным циклом проекта. Однако проекты растут очень быстро: увеличивается количество модулей, тестов, зависимостей, используемых плагинов. И всего лишь за год легковесный проект, на сборку которого уходило 5 минут, превращается в монстра, который пожирает время разработчиков 30-минутной сборкой. Чтобы справится с этой проблемой разработчикам приходится постоянно чистить свой код и бороться со скоростью выполнения тестов. Это верное решение, но не следует забывать о том, что и сам процесс сборки можно улучшить. В этом докладе будет рассмотрено, как при помощи простых и нехитрых шагов можно оптимизировать работу с зависимостями и обогатить скрипты сборки полезными плагинами. Также будут обсуждаться тонкости конфигурации основных плагинов и особенности работы с командной строкой, которые появились в последней версии Maven.
About Spring in pictures.
Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.
Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.
Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
Why should we know about Spring internals? It works! So use it and enjoy! However, as always, in order to use Spring in most efficient way, you must know, what is under the fork. Only in case you really understand its internals you will be able to use all power of Spring. You will be able to customize this framework according to challenges of your project, to achieve best performance and solve any problem without applying to Spring-support center. ;) Here are several topics about Spring internals, which will be covered during this session (with examples for each one): What is Spring impact on the performance of your application? What are the phases of Spring lifecycle? What is ApplicationContext structure? “You can’t do it with Spring!” – or maybe you can?
The document summarizes a presentation about the Phoenix framework. It includes:
1. An introduction from Chris McCord, inventor of Phoenix, about how Phoenix is similar to and different from Ruby on Rails.
2. Sections discussing how Phoenix draws inspiration from Rails but is optimized for concurrency using the Erlang VM and functional programming principles like immutability.
3. Advice that incremental adoption of Phoenix for new features or rewrites is better than sudden wholesale changes, to minimize disruption for developers and users.
This is a presentation given on October 24 by Michael Uzquiano of Cloud CMS (http://www.cloudcms.com) at the MongoDB Boston conference.
In this presentation, we cover Hazelcast - an in-memory data grid that provides distributed object persistence across multiple nodes in a cluster. When backed by MongoDB, objects are naturally written to Mongo by Hazelcast. The integration points are clean and easy to implement.
We cover a few simple cases along with code samples to provide the MongoDB community with some ideas of how to integrate Hazelcast into their own MongoDB Java applications.
«Бутылочное горлышко многопоточных программ – кто виноват, и что делать. Мастер-класс.»
BitByte: 20 апреля 2013, Санкт-Петербург
http://bitbyte.itmozg.ru/
When you work in a small collocated team many engineering practices and approaches are relatively easy to use and adapt. In large project with many teams working on the same product this task is not so simple. I want to share experience report in implementing Code Review practice in big product development team (more than 150 people, 10+ feature teams). In this talk we will review what approaches works in such setup and what don’t work, what tools and additional practices are needed to support Code Review and make it more effective, what difficulties and blockers will you probably see in the real life cases, what useful metrics could be produced by this practice.
In this webinar we will compare the complexities involved in Terracotta with the code/configuration changes to migrate to Hazelcast. You will learn about important features of Hazelcast such as IMDG capabilities, off-heap data storage, distributed collections, etc. and the feature-rich product portfolio of Hazelcast. We will cover how Hazelcast can scale up and out dynamically and without downtime against the static configuration of Terracotta. Expect to leave the webinar being more educated about Hazelcast in terms of architecture, important features and best practices.
We’ll cover these topics:
- Hazelcast architecture and features
- Terracotta distributed architecture
- Scale – Vertical + Horizontal = Showcase no downtime feature in Hazelcast
- BigMemory vs. HDC
- Ease of installation – two jars against multiple jars
- Config and Code changes – cache vs. maps, off-heap vs. HDC
- Portability of Client APIs – IMap, IQueue, Topics, etc.
- Added functionalities – Showcase IExecutorService, EntryProcessors, Multimap, etc.
- DSO – Showcase EntryProcessors taking place of DSO
- Live Q&A
Presenter:
Rahul Gupta, Senior Solutions Architect
Rahul is a technology-driven professional with 12+ years of experience in building and architecting highly scalable and concurrent, low latency business critical distributed infrastructure. His expertise lies in Big Data and Real Time Analytics space where he specializes in big data governing technologies and Enterprise Architecture. Rahul is an expert in working with decision makers across different business verticals within an organization and guiding them in right decision making through in-depth technical understanding, analysis and evaluation procedures to bring home critical deals with high business values.
Of course Java 8 is all about lambda expressions and this new wonderful Stream API. Now the question is, what's left in Java 8, once we've removed everything : lambdas, streams, collectors, java FX and Nashorn ? This presentation gathered all these new diamonds, scattered all around the JDK, brand new classes, and new methods in existing classes.
The document discusses new features in Java related to numbers and strings. It describes new methods like max(), min(), and sum() that are available on number wrapper classes. It also discusses improved ways to concatenate strings in Java 8 using StringJoiner and the join() method on the String class. The document notes how these features can make code more readable by allowing method references.
Gamification in outsourcing company: experience report.Mikalai Alimenkou
Most of us used to hear word gamification only for end user engagement into product usage. Some of us know about usage of similar approaches in product development teams to improve and tune development process. But almost nobody believes that gamification is possible in the context of outsourcing companies and teams. This talk is experience report of gamification usage on very large project with detailed reusable framework demonstration. If you want to bring some fun and really engage your team, then this talk is for you.
This document discusses Java 8 features including Optional, lambdas, and Stream API. It provides advice on properly using Optional to avoid null checks, keeping lambda expressions simple, and only using streams for functional-style operations without side effects. The document recommends using method references when possible and external libraries like jOOL and StreamEx that extend the stream functionality. It concludes by providing contact information for the authors to ask additional questions.
Developers want to make very few errors in their code and to spot them as early as possible: with the help of unit tests, or earlier, during compilation, or best of all, immediately after they typed something wrong in their IDE. This is what static code analyzers are for. Some of them are built-in, others need to be run separately, some check just about any code, the others require it to be annotated first, and there are tools that are a little bit of all. Do the ends justify the means? Is it even worth trying? What kind of errors can be spotted by static code analysis? How sure can we be if what an analyzer gives us is a real error or a false positive? This talk hopefully helps you answer these questions.
Вводная лекция в язык C#, для тех кто знает программирование и в особенности C++. В статье будет уделено внимание наиболее важным отличиям языков, будут обсуждаться вопросы производительности и эффективного кода.
Другие интересные статьи по C# ищите тут: http://itw66.ru/blog/c_sharp/
Написание компактного и эффективного кода в C#: http://itw66.ru/blog/c_sharp/520.html
Olexandra Dmytrenko
QA Automating at EPAM Systems
I'll show you how to switch from writing standard code using good old Java7 into writing it using functional way presented in Java8. The training is counted on beginners in the subject who like discovering the new horizons or for those who want to become more firm in using the new lambda features.
Java 8, самой заметной фичей которой стало появление лямбд, вышла два года назад, а в этом году мы даже начали её использовать в продакшен коде Идеи. Такое заметное нововведение в языке вызывает множество вопросов. Какие возможности перед нами открываются и какие проблемы при неаккуратном использовании лямбд могут возникнуть, как лямбды устроены внутри, во что они компилируются и как исполняются — вот темы, которые мы обсудим на докладе.
Статический анализ кода: Что? Как? Зачем?Andrey Karpov
Методология статического анализа год за годом зарекомендовывает себя в поисках дефектов в исходном коде программ.
Максим расскажет про:
- методологию статического анализа и какие плюсы и минусы у нее есть;
- технологии этой методологии, которые позволяют выявлять разнообразнейшие дефекты в коде;
- интересные примеры ошибок в реальных проектах, которые были найдены при помощи статического анализа;
- интеграцию инструментов статического анализа в проекты любой сложности, и почему так важно регулярное использование подобных инструментов.
2. Вместо эпиграфа
Не изобретайте колесо. Если вам нужно сделать нечто, что кажется
вполне обычным, в библиотеках уже может быть класс, который делает
это. Вообще говоря, программный код в библиотеке наверняка окажется
лучше кода, который вы напишете сами, а со временем он может стать
еще лучше. Мы не ставим под сомнение ваши способности как
программиста, однако библиотечному коду уделяется гораздо больше
внимания, чем может позволить себе средний разработчик при
реализации тех же функций.
Джошуа Блох.
Эффективное программирование на Java.
2 Статья 47 “Изучите библиотеки и пользуйтесь ими”
3. Философия библиотеки
● Тщательно разработана
● Протестирована
● Оптимизирована
● Только повсеместно используемые
функции попадают в библиотеку
3
4. Зачем использовать GUAVA
● Сэкономить значительное количество
написанного кода
● Избежать написания кода, который
трудно отлаживать и в котором легко
ошибиться
● Улучшить читабельность
● Улучшить скорость работы программы. 4
5. Особенность удаления фич
● В отличие от JDK удаляют
нежелательное поведение через
некоторое время
● @Beta API
● @Deprecated non @Beta компоненты
удаляются через 18 месяцев
5
6. Базовые утилиты
● Работа с null. Optional
● Preconditions
● Objects, toString, equals,
hashCode
● Компараторы с Ordering
6
7. Использование и избежание работы с
null
● null - источник множества ошибок.
● null быстр и нужно научится его правильно
использовать, где это необходимо, и избегать во
всех остальных случаях.
● Многие утилиты GUAVA где недопустимы null’ы
бросают ошибку.
7
8. Optional<T>
Not null reference of T Present Optional<T>
null reference of T
Absent Optional<T>
8
15. Preconditions
int positive = 1;
checkArgument(positive > 0, "Number %s must be a positive", positive); // IllegalArgumentException:
//Number 1 must be a negative
checkArgument(positive < 0, "Number %s must be a negative", positive); // IllegalArgumentException:
//Number 1 must be a negative
Object nullValue = null;
checkNotNull(nullValue, "Value mast be not null"); // NullPointerException: Value mast be not null
checkState(positive < 0); // IllegalStateException
checkElementIndex(5, 6);
checkElementIndex(6, 6); // IndexOutOfBoundsException: index (6) must be less than size (6)
checkPositionIndex(6, 6);
checkPositionIndexes(3, 4, 4);
15
23. Ordering
● Ordering<T> - наследник
Comparator<T>
● В Ordering реализованы методы
использующие порядок: min, max, sort и
т.д.
23
24. Ordering<T>. Создание
● Ordering.natural() - естественный порядок,
основанный на функции compare(T,T)
● Ordering.usingToString() - лексикографический
порядок, строковых представлений (toString)
● Ordering.from(Comparator)
● Наследник Ordering
24
25. Ordering<T>. Использование
greatestOf(Iterable iterable, int k)
See also: leastOf
isOrdered(Iterable)
See also: isStricklyOrdered
sortedCopy(Iterable)
See also: immutableSortedCopy
min(E, E)
See also: max(E, E)
min(E, E, E, E...)
See also: max(E, E, E, E...)
min(Iterable)
See also: max(Iterable), min(Iterator), max(Iterator)
25
28. Список Person
private static List<Person> createPersonList()
{
return Lists.newArrayList(
new Person("Egor", "Chernyshev", 24),
new Person("Anton", "Borisov", 36),
new Person("Elena", "Petrova", 18),
new Person("Maxim", "Lobanov", 65),
new Person(null, "Alexandrova", 24));
}
28
31. GUAVA Collections
● ImmutableCollections
● Новые коллекции в Guava
● Утилитарные классы Sets, Lists, Maps…
● Утилиты для расширения java коллекций
31
33. Чем хороши Immutable objects?
● Безопасное использование в untrusted
библиотеках.
● Потоко безопасны.
● Хороши для хранения констант, так как
есть гарантия неизменяемости.
33
34. Interface JDK или Guava Immutable version
Collection JDK ImmutableCollection
List JDK ImmutableList
Set JDK ImmutableSet
SortedSet /
NavigableSet
JDK ImmutableSortedSet
Map JDK ImmutableMap
SortedMap JDK ImmutableSortedMap
34 Multiset Guava ImmutableMultiset
35. Interface JDK или Guava Immutable version
SortedMultiset Guava ImmutableSortedMultiset
Multimap Guava ImmutableMultimap
ListMultimap Guava ImmutableListMultimap
SetMultimap Guava ImmutableSetMultimap
BiMap Guava ImmutableSetMultimap
ClassToInstanceM
ap
Guava ImmutableClassToInstanceMap
35 Table Guava ImmutableTable
39. copyOf умнее, чем вы думаете
● copyOf пытается избежать полного
копирования объектов.
● В общем случае ImmutableXXX.copyOf
(ImmutableXXX) пытается выполнится
за O(1), за исключением некоторых
случаев
39
43. Multiset. Пример
Подсчет количества каждого символа в тексте:
Multiset<Character> toCharsMultiset(String text)
{
return HashMultiset.create(Chars.asList(text.toCharArray()));
}
43
44. Multiset. Реализации
Map Соответствующий Multiset Допускает null?
HashMap HashMultiset Да
TreeMap TreeMultiset Да (если компаратор
поддерживает)
LinkedHashMap LinkedHashMultiset Да
ConcurrentHashMap ConcurrentHashMultiset Нет
ImmutableMap ImmutableMultiset Нет
44
48. Multimap<K,V>. Реализации
Реализация Ключи ведут себя как... Значения ведут себя как...
ArrayListMultimap HashMap ArrayList
HashMultiMap HasMap HashSet
LinkedListMultimap LinkedHashMap LinkedList
LinkedHashMultiMap LinkedHashMap LinkedHashSet
TreeMultimap TreeMap TreeSet
ImmutableListMultimap ImmutableMap ImmutableList
ImmutableSetMultimap ImmutableMap ImmutableSet
48
49. Multimap. Пример
private static Function<Person, String> FIRST_NAME_EXTRACTOR = new
Function<Person, String>()
{
@Override
public String apply(Person input)
{
return input.getFirstName();
}
};
49
50. Multimap. Пример
List<Person> PERSONS = Lists.newArrayList(
new Person("Egor", "Chernyshev", 24),
new Person("Anton", "Borisov", 36),
new Person("Elena", "Petrova", 18),
new Person("Elena", "Birkova", 11),
new Person("Maxim", "Lobanov", 65));
Multimap<String, Person> index = Multimaps.index(PERSONS, FIRST_NAME_EXTRACTOR);
50
52. BiMap<K,V>
BiMap<V, K> - это Map<K, V>, в которой
● Добавлен метод BiMap<V, K> inverse().
● Есть проверка на уникальность значений.
● values() возвращает Set<V>.
52
55. Table<R, C, V>
● Table - это способ хранения индекса
объекта по двум ключам R и C.
● Table<R,C,V> заменяет неуклюжую
реализацию структуры
Map<R, Map<C, V>>
55
56. Table<R, C, V>. Представления
Table<R,C,V>.rowMap() Map<R, Map<C,V>>
Table<R,C,V>.rowKeySet() Set<R>
Table<R,C,V>.row(r) Map<C,V>
columnMap(),
columnKeySet(), column(c)
Аналогично, row. Column access по
производительности работает медленнее, чем row
access из за структуры данных.
Table<R,C,V>.cellSet() Set<Table.Cell<R,C,V>>
56
57. Table<R, C, V>. Реализации
Реализация На основе структуры
HashBasedTable HashMap<R, HashMap<C, V>>
TreeBasedTable TreeMap<R, TreeMap<C, V>>
ImmutableTable ImmutableMap<R, ImmutableMap<C, V>>
ArrayTable Двумерный массив. Хорошо подходит для
задач, с сильно заполненными таблицами.
57
60. public interface MegaService {}
public class SuperMegaService implements MegaService{}
public class SuperMegaBupperService implements MegaService{}
…
private static final ClassToInstanceMap<MegaService> REGISTRY = MutableClassToInstanceMap.create();
…
REGISTRY.putInstance(SuperMegaService.class, new SuperMegaService());// OK
REGISTRY.putInstance(SuperMegaBupperService.class, new SuperMegaBupperService());// OK
REGISTRY.putInstance(MegaService.class, new SuperMegaBupperService());// OK
REGISTRY.putInstance(SuperMegaService.class, new SuperMegaBupperService()); // Ошибка компиляции
REGISTRY.putInstance(String.class, "qqqq"); // Ошибка компиляции
REGISTRY.put(String.class, "qqqq"); // Ошибка компиляции
REGISTRY.getInstance(MegaService.class);// OK
REGISTRY.getInstance(String.class);// Ошибка компиляции
60
69. Iterables
● Guava предпочитает Iterable вместо
Collection
● Многие Iterable являются Lazy
● Утилита FluentItrable, оборачивает
Iterable и предоставляет набор
методов для работы в функцинальном
стиле. 69
70. Lists
Метод Описание
partiton(List, int) List<List> - разбиение списка на подсписки
определенной длины.
reverse(List) Развернутое представление списка
70
71. Sets
Метод Описание
union(Set, Set) Объединение множеств
intersection(Set, Set) Пересечение
difference(Set, Set) Разность
symmetricDifference(Set, Set) симметричная разность
powerSet(Set) Множество всех подмножеств
71
73. Maps.uniqueIndex()
Maps.uniqueIndex(Lists.newArrayList("dddd", "ddddd", "qwcccccde"), new Function<String, Integer>()
{
@Override
public Integer apply(String input)
{
return input.length();
}
});
//{4=dddd, 5=ddddd, 9=qwcccccde}
● Выбросится ошибка, если Function
73 вернет неуникальное значение
74. MapDifference d = Maps.difference()
entriesOnlyOnLeft() entriesInCommon() entriesOnlyOnRight()
entriesDiffering()
74
75. Multimaps
Метод Описание
index(Iterable, Function) Построение индекса коллекции по ключевой
функции
invertFrom(Multimap, Multimap) Разворот Map’ы (<K,V> -> <V,K>)
forMap(Map) Преобразвание Map<K,V> в Multimap<K,V>
75
76. Tables
Метод Описание
transpose(Table<R,C,V>) Транспонирование таблицы Table<R,C,V> ->
Table<C,R,V>
76
81. PeekingIterator
List<String> result = Lists.newArrayList();
PeekingIterator<String> iter = Iterators.peekingIterator(source.iterator());
while (iter.hasNext()) {
String current = iter.next();
while (iter.hasNext() && iter.peek().equals(current)) {
// skip this duplicate element
iter.next();
}
result.add(current);
}
81
82. AbstractIterator
public static Iterator<String> skipNulls(final Iterator<String> in) {
return new AbstractIterator<String>() {
protected String computeNext() {
while (in.hasNext()) {
String s = in.next();
if (s != null) {
return s;
}
}
return endOfData();
}
};
}
82
86. Cache. Добавление значения
CacheLoader
/**
* Медленная операция получения человека по Web сервису
* из внешней системы
*/
private Person loadPersonByWebService(String key)
{
return new Person("Anton", "Borisow", 88);
}
86
95. Cache. Когда происходит eviction
● В момент записи нового значения
● Иногда (если записей в кэш мало) при
получении значения по ключу
● Кэш не обслуживается отдельным
95 потоком!
96. Cache. Прочие возможности
● Statistic:
Включение: CacheBuilder.recordStats();
Получение: CacheStats stats = Cache.stats();
Использование:
● stats.hitRate() - количество попаданий
● stats.averageLoadPenalty() - среднее время на загрузку
новых значений
● stats.evictionCount() - количество eviction’ов
● asMap
96
98. ListenableFuture
● Расширяет Future - позволяет
регистрировать Callback на момент
выполнения операции.
● Callback будет вызван один раз.
● Callback обрабатывает ошибки с
помщью onFaiture() метода.
98
102. Service
● Интерфейс Service - это объект с рабочим
состоянием и методами остановки и запуска.
● Service имеет ряд предопределенных
состояний.
● Существуют базовые абстрактные
реализации, которые необходимо
переопределять для написания собственных
102 служб и сервисов.
103. Использование Service
NEW STARTING RUNNING STOPPING TERMINATED
Метод Описание
startAsync() Запуск
stopAsync() Остановка
state() Статус
103
105. ServiceManger
Метод Описание
startAsync() Стартует все службы
stopAsync() Останавливает все службы
addListener Добавление листенеров на смены статусов
awaitHealthy() дождаться пока все службы не станут RUNNING
awaitStopped() дождаться пока все службы не будут остановлены
isHealthy() true, если все службы RUNNING
servicesByState() ultimap сервисов сгрупированных по состояниям
105 startupTimes() Map сервисов с временами старта. Отсортированная
110. Strings
Метод Описание
isNullOrEmpty(str) true,если str == null или str.length() == 0
nullToEmpty(str) Преобразуется null в “”
emptyToNull(str) Преобразует “” в null
repeat(str, int) Повторяет str строку int раз
110