This document discusses LEGO as a framework for building distributed systems in Scala. It begins with the origins and principles of LEGO, then explores how Scala has been used in applications with LEGO. It concludes with some reflections on promoting LEGO.
Scalaz-stream introduced the Scala ecosystem to purely functional streams. Although widely deployed in production at Verizon, SlamData, and elsewhere, the last release of scalaz-stream was October 23rd, 2016, and newer projects such as FS2, Monix Iterant, and others have risen to fill the gap, each addressing different use cases in the functional programming community. In this talk, John A. De Goes, architect of the Scalaz 8 effect system, unveils a new design for a next-generation version of scalaz-stream. Designed to embrace the powerful features of the Scalaz 8 effect system—features not available in any other effect type—this design features higher-performance, stronger guarantees, and far less code than previous incarnations. You are invited to discover the practicality of functional programming, as well as its elegance, beauty, and composability, in this unique presentation available exclusively at Scale By the Bay.
The Design of the Scalaz 8 Effect SystemJohn De Goes
Purely functional Scala code needs something like Haskell's IO monad—a construct that allows functional programs to interact with external, effectful systems in a referentially transparent way. To date, most effect systems for Scala have fallen into one of two categories: pure, but slow or inexpressive; or fast and expressive, but impure and unprincipled. In this talk, John A. De Goes, the architect of Scalaz 8’s new effect system, introduces a novel solution that’s up to 100x faster than Future and Cats Effect, in a principled, modular design that ships with all the powerful primitives necessary for building complex, real-world, high-performance, concurrent functional programs.
Thanks to built-in concurrency, high performance, lawful semantics, and rich expressivity, Scalaz 8's effect system may just be the effect system to attract the mainstream Scala developers who aren't familiar with functional programming.
At the heart of data processing, event-sourcing, actors, and much more is the queue—a data structure that allows producers to pass work to consumers in a flexible way. On the JVM, most libraries, including Akka, are powered by Java concurrent queues, which are reliable but were designed in a different era, for synchronous (blocking) procedural code. In this presentation, John A. De Goes—architect of the Scalaz 8 effect system—introduces IOQueue, a new type of queue powered by the Scalaz 8 IO monad. IOQueue never blocks and provides seamless, composable back-pressure across an entire application, without users having to think about the problem or write any special code. John will discuss how IOQueue achieves these remarkable properties, and show how the structure can be used to solve hard problems with just a few lines of type-safe, leak-free, composable Scala code. Come learn about the power of Scalaz to solve the hard problems of software development, in a principled way, without compromises.
Halogen is a popular choice for building front-end user-interfaces with PureScript. Often described as a purely functional version of React, Halogen allows building user-interfaces by composing declarative, self-contained components, including effectful components those built from third-party Javascript libraries.
In this presentation, John presents a high-level summary of where Halogen has come from, how it works right now, and what are the main drawbacks to both FRP and React. John then suggests that incremental computation should be the foundation for the next major version of Halogen, and sketches out a possible way of achieving that in a declarative fashion.
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
Rx и Kotlin стали самыми модными трендами Android разработки в последнее время. Мы выпустили два приложения с архитектурой, построенной вокруг Rx, где нет ни одной строки на Java. Насколько удобно работать с этими инструментами? В своём докладе я расскажу, с какими трудностями мы столкнулись, как их победили, а также продемонстрирую несколько крутых и несложных подходов к разработке на этом стеке.
"Delegates, Delegates everywhere" Владимир МироновAvitoTech
Поговорим про delegated properties и все, что с ними связано. Узнаем, зачем они нужны, какие delegated properties предоставляет стандартная библиотека, напишем несколько своих и рассмотрим более сложные примеры, которые могут быть полезны в мире android-разработки. Мы также посмотрим, во что delegated properties превращаются во время компиляции, и какие сюрпризы нас могут ожидать.
Scalaz-stream introduced the Scala ecosystem to purely functional streams. Although widely deployed in production at Verizon, SlamData, and elsewhere, the last release of scalaz-stream was October 23rd, 2016, and newer projects such as FS2, Monix Iterant, and others have risen to fill the gap, each addressing different use cases in the functional programming community. In this talk, John A. De Goes, architect of the Scalaz 8 effect system, unveils a new design for a next-generation version of scalaz-stream. Designed to embrace the powerful features of the Scalaz 8 effect system—features not available in any other effect type—this design features higher-performance, stronger guarantees, and far less code than previous incarnations. You are invited to discover the practicality of functional programming, as well as its elegance, beauty, and composability, in this unique presentation available exclusively at Scale By the Bay.
The Design of the Scalaz 8 Effect SystemJohn De Goes
Purely functional Scala code needs something like Haskell's IO monad—a construct that allows functional programs to interact with external, effectful systems in a referentially transparent way. To date, most effect systems for Scala have fallen into one of two categories: pure, but slow or inexpressive; or fast and expressive, but impure and unprincipled. In this talk, John A. De Goes, the architect of Scalaz 8’s new effect system, introduces a novel solution that’s up to 100x faster than Future and Cats Effect, in a principled, modular design that ships with all the powerful primitives necessary for building complex, real-world, high-performance, concurrent functional programs.
Thanks to built-in concurrency, high performance, lawful semantics, and rich expressivity, Scalaz 8's effect system may just be the effect system to attract the mainstream Scala developers who aren't familiar with functional programming.
At the heart of data processing, event-sourcing, actors, and much more is the queue—a data structure that allows producers to pass work to consumers in a flexible way. On the JVM, most libraries, including Akka, are powered by Java concurrent queues, which are reliable but were designed in a different era, for synchronous (blocking) procedural code. In this presentation, John A. De Goes—architect of the Scalaz 8 effect system—introduces IOQueue, a new type of queue powered by the Scalaz 8 IO monad. IOQueue never blocks and provides seamless, composable back-pressure across an entire application, without users having to think about the problem or write any special code. John will discuss how IOQueue achieves these remarkable properties, and show how the structure can be used to solve hard problems with just a few lines of type-safe, leak-free, composable Scala code. Come learn about the power of Scalaz to solve the hard problems of software development, in a principled way, without compromises.
Halogen is a popular choice for building front-end user-interfaces with PureScript. Often described as a purely functional version of React, Halogen allows building user-interfaces by composing declarative, self-contained components, including effectful components those built from third-party Javascript libraries.
In this presentation, John presents a high-level summary of where Halogen has come from, how it works right now, and what are the main drawbacks to both FRP and React. John then suggests that incremental computation should be the foundation for the next major version of Halogen, and sketches out a possible way of achieving that in a declarative fashion.
"Kotlin и rx в android" Дмитрий Воронин (Avito)AvitoTech
Rx и Kotlin стали самыми модными трендами Android разработки в последнее время. Мы выпустили два приложения с архитектурой, построенной вокруг Rx, где нет ни одной строки на Java. Насколько удобно работать с этими инструментами? В своём докладе я расскажу, с какими трудностями мы столкнулись, как их победили, а также продемонстрирую несколько крутых и несложных подходов к разработке на этом стеке.
"Delegates, Delegates everywhere" Владимир МироновAvitoTech
Поговорим про delegated properties и все, что с ними связано. Узнаем, зачем они нужны, какие delegated properties предоставляет стандартная библиотека, напишем несколько своих и рассмотрим более сложные примеры, которые могут быть полезны в мире android-разработки. Мы также посмотрим, во что delegated properties превращаются во время компиляции, и какие сюрпризы нас могут ожидать.
Free monads and free applicatives have proven an incredibly useful tool in repertoire of the functional programmer: they separate concerns, encourage denotational semantics for program specification, allow easy and type-safe mocking of purely functional code, and allow dynamic introspection and optimization.
Despite these benefits, free monads are notoriously constrained: by themselves, they cannot handle parallelism (only sequentiality), and because they provide only a monad, richer structures (such as monads that fail, or monads that support alternation) cannot be expressed without crude hacks that limit composability and expressiveness.
In this session, John A. De Goes shows how the free monad can be deconstructed for its individual features, and then rebuilt using a more powerful technique that enables more extensibility. The resulting structure — no longer technically a "free monad" — allows reification of as few or as many aspects of computation as are necessary to model the problem domain.
After the session, attendees will know how to augment their existing free programs to add parallelism, racing, failure, and other aspects of computation as required by their problem. In addition, through this thorough deconstruction and reconstruction of the free monad, attendees will have a very deep understanding of reified computation and why the free monad has the structure and limitations it does.
PHP 8.0 is expected to be released by the end of the year, so it’s time to take a first look at the next major version of PHP. Attributes, union types, and a just-in-time compiler are likely the flagship features of this release, but there are many more improvements to be excited about. As PHP 8.0 is a major version, this release also includes backwards-incompatible changes, many of which are centered around stricter error handling and more type safety.
This talk will discuss new features already implemented in PHP 8, backwards-compatibility breaks to watch out for, as well as some features that are still under discussion.
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...GeeksLab Odessa
CSP (i.e. 'go-like' channels and 'Occam-like' transputers) can be useful programming technique for structuring asynchronous blocking tasks. Author own implementation of CSP [scala-gopher] will be presented.
Découverte d'algèbre, d'interpréteur par la création d'un DSL pour la base de données Aerospike. Le tout est implémenté dans le langage Scala avec un style fonctionnel.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
Go provides:
+ Concurrent execution
+ Synchronization and messaging
+ Multi-way concurrent control
Go does NOT provide direct thread manipulation
- Go multithreading is fully managed by Go runtime.
- In Go you use goroutines in place of threads
Learn about Goroutines, channels and standard library
Welcome to experience the genuine Part Time Business opportunity. Go through the slides which will highlight the business potential, its unique concept and its momentum. Proper training from company and support will be given from your basic level to your highest growth
Free monads and free applicatives have proven an incredibly useful tool in repertoire of the functional programmer: they separate concerns, encourage denotational semantics for program specification, allow easy and type-safe mocking of purely functional code, and allow dynamic introspection and optimization.
Despite these benefits, free monads are notoriously constrained: by themselves, they cannot handle parallelism (only sequentiality), and because they provide only a monad, richer structures (such as monads that fail, or monads that support alternation) cannot be expressed without crude hacks that limit composability and expressiveness.
In this session, John A. De Goes shows how the free monad can be deconstructed for its individual features, and then rebuilt using a more powerful technique that enables more extensibility. The resulting structure — no longer technically a "free monad" — allows reification of as few or as many aspects of computation as are necessary to model the problem domain.
After the session, attendees will know how to augment their existing free programs to add parallelism, racing, failure, and other aspects of computation as required by their problem. In addition, through this thorough deconstruction and reconstruction of the free monad, attendees will have a very deep understanding of reified computation and why the free monad has the structure and limitations it does.
PHP 8.0 is expected to be released by the end of the year, so it’s time to take a first look at the next major version of PHP. Attributes, union types, and a just-in-time compiler are likely the flagship features of this release, but there are many more improvements to be excited about. As PHP 8.0 is a major version, this release also includes backwards-incompatible changes, many of which are centered around stricter error handling and more type safety.
This talk will discuss new features already implemented in PHP 8, backwards-compatibility breaks to watch out for, as well as some features that are still under discussion.
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...GeeksLab Odessa
CSP (i.e. 'go-like' channels and 'Occam-like' transputers) can be useful programming technique for structuring asynchronous blocking tasks. Author own implementation of CSP [scala-gopher] will be presented.
Découverte d'algèbre, d'interpréteur par la création d'un DSL pour la base de données Aerospike. Le tout est implémenté dans le langage Scala avec un style fonctionnel.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
Go provides:
+ Concurrent execution
+ Synchronization and messaging
+ Multi-way concurrent control
Go does NOT provide direct thread manipulation
- Go multithreading is fully managed by Go runtime.
- In Go you use goroutines in place of threads
Learn about Goroutines, channels and standard library
Welcome to experience the genuine Part Time Business opportunity. Go through the slides which will highlight the business potential, its unique concept and its momentum. Proper training from company and support will be given from your basic level to your highest growth
Powerpoint presentation that outlines the history and achievements of SiSTeR Technologies and their U.S. Patent award-winning automated video technology system and how it's revolutionized the automotive advertising industry since 2005.
SiSTeR Technologies provides the video production and distribution models which have allow the industry pioneer to lead the way in automotive video advertising in the areas of video production, video distribution, mobile devices, social media and video search engine optimization (vSEO) - all for the goal of increasing a dealer's online digital presence, leads and sales generation and ROI
Automated Video Marketing System & Video SEO - Automotive & Real Estate Solut...Sister Technologies
PowerPoint presentation that outlines the history and achievements of SiSTeR Technologies and their U.S. Patent award-winning automated video technology system and how it's revolutionized the automotive advertising industry since 2005.
SiSTeR Technologies provides the video production and distribution models which empower the industry pioneer to lead the way in automotive video advertising in the areas of video production, video distribution, mobile devices, social media and video search engine optimization - all for the goal of increasing a dealer's online digital presence, leads and sales generation and ROI.
GDG Devfest 2019 - Build go kit microservices at kubernetes with easeKAI CHU CHUNG
Gokit is microservice tookit and use Service/Endpoint/Transport to strict separation of concerns design. This talk to use go-kit develop microservice application integrate with consul, zipkin, prometheus, etc service and deploy on Kubernetes.
Wprowadzenie do technologii Big Data / Intro to Big Data EcosystemSages
Introduction to Hadoop Map Reduce, Pig, Hive and Ambari technologies.
Workshop deck prepared and presented on September 5th 2015 by Radosław Stankiewicz.
During that the day participants had also the possibility to go through prepared tutorials and test their analysis on real cluster.
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
SubScript - это расширение языка Scala, добавляющее поддержку конструкций и синтаксиса аглебры общающихся процессов (Algebra of Communicating Processes, ACP). SubScript является перспективным расширением, применимым как для разработки высоконагруженных параллельных систем, так и для простых персональных приложений.
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
Defining customized scalable aggregation logic is one of Apache Spark’s most powerful features. User Defined Aggregate Functions (UDAF) are a flexible mechanism for extending both Spark data frames and Structured Streaming with new functionality ranging from specialized summary techniques to building blocks for exploratory data analysis.
1. what is the different unbuffered and buffered channel?
2. how to implement a job queue in golang?
3. how to stop the worker in a container?
4. Shutdown with Sigterm Handling
5. Canceling Workers without Context
6. Graceful shutdown with worker
7. How to auto-scaling build agent?
8. How to cancel the current Job?
Big Data Day LA 2016/ Hadoop/ Spark/ Kafka track - Iterative Spark Developmen...Data Con LA
This presentation will explore how Bloomberg uses Spark, with its formidable computational model for distributed, high-performance analytics, to take this process to the next level, and look into one of the innovative practices the team is currently developing to increase efficiency: the introduction of a logical signature for datasets.
Streams are often underestimated and skipped as possible solutions. In many cases, we created much more complex solutions than their streams counterpart. Why?
It's hard to answer, but in this presentation, I would like to tell you a story about how we started to use FS2, without sacrificing purity and code readability. (https://github.com/functional-streams-for-scala/fs2)
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/
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
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.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
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.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
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.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
May Marketo Masterclass, London MUG May 22 2024.pdfAdele Miller
Can't make Adobe Summit in Vegas? No sweat because the EMEA Marketo Engage Champions are coming to London to share their Summit sessions, insights and more!
This is a MUG with a twist you don't want to miss.
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.
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
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.
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.
31. Trait or Object ?
trait T {
def put(a: Any) {
println(a)
}
}
class A extends T {
def hi() {
put("hi")
}
}
object O {
def put(a: Any) {
println(a)
}
}
class B {
import O._
def hi() {
put("hi")
}
}
32. Trait or Object ?
trait A {
case class B(i: Int)
}
class C extends A {
def !(a:Any) = a match {
case B(0) => println("B(0)")
case b: B => println("B")
case x => println(s"Oops, $x")
}
}
class D extends A {
new C ! B(0)
}
new D // Oops, B(0)
object A {
case class B(i: Int)
}
class C {
import A._
def !(a:Any) = a match {
case B(0) => println("B(0)")
case b: B => println("B")
case x => println(s"Oops, $x")
}
}
import A._
new C ! B(0) // B(0)
33. Trait, no Object !
trait T {
def size: Int
def isEmpty = size == 0
}
class A extends T {
def size = 5
}
new A().isEmpty // false
36. Type
type Frame = (StartLine, Headers, Option[Payload])
type StartLine = String
type Headers = List[String]
type Payload = (Array[Byte], Zip)
type Zip = Boolean
case class Frame(startLine: String, headers: List[String], content: Option[Payload])
case class Payload(data: Array[Byte], zip: Boolean)
37. WARNING !!!
scala> type Headers = List[String]
defined type alias Headers
scala> :pas
List(1, 2, 3) match {
case _: Headers => println("wrong!")
case _ => println("right!")
}
<console>:10: warning: fruitless type test: a value of type List[Int] cannot also
be a List[String] (the underlying of Headers) (but still might match its erasure)
case _: Headers => println("wrong!")
^
wrong!
38. Val
scala> val Headers = List
Headers: scala.collection.immutable.List.type = scala.collection.immutable.
List$@7be117eb
scala> val headers = Headers("mid:1")
headers: List[String] = List(mid:1)
scala> val Headers(a) = List("mid:1")
a: String = mid:1
39. Val & Type
package object transport {
type Event = pipeline.Event
type Command = pipeline.Command
type Write = pipeline.Write
val Write = pipeline.Write
type Read = pipeline.Read
val Read = pipeline.Read
type Stage = pipeline.Stage[Context]
}
41. Default Supervisor Strategy
import akka.actor._
class Handler(var i: Int) extends Actor {
def receive = {
case "incr" => i += 1
case "show" => println(i)
case "boom" => throw new Exception
}
}
object Handler {
def props(i: Int) = {
Props(classOf[Handler], i)
}
}
val system = ActorSystem("fun")
val h = system.actorOf(Handler.props(1))
h ! "show" // 1
h ! "incr"
h ! "show" // 2
h ! "boom" // Exception
h ! "show" // 1
42. WARNING !!!
class Connector(remote: Address) extends Actor {
import context.system
IO(Tcp) ! Tcp.Connect(remote) // be careful
def receive = {
case Tcp.Connected(_, locale) =>
// handling
case Tcp.CommandFailed(_: Tcp.Connect) =>
context stop self
}
}
43. WARNING !!!
class Connector(remote: Address) extends Actor {
import context.system
IO(Tcp) ! Tcp.Connect(remote)
def receive = {...}
// not work
override def supervisorStrategy = SupervisorStrategy.stoppingStrategy
}
44. Solution
class ConnectingSupervisor extends Actor { // solution 1
def receive = {
case remote: Address =>
val c = context.actorOf(Connector.props(remote))
...
}
override def supervisorStrategy = SupervisorStrategy.stoppingStrategy
}
class Connector(remote: Address) extends Actor { // solution 2
override def preRestart(reason: Throwable, message: Option[Any]) = {
context stop self
}
}
45. No Sender
class Pong extends Actor {
def receive = {
case "ping" => sender() ! "pong"
}
}
class Ping(pong: ActorRef) extends Actor {
pong ! "ping"
def receive = ...
}
class Ping(pong: ActorRef) {
pong ! "ping"
}
def !(message: Any)(implicit sender: ActorRef = Actor.noSender): Unit