Introduction to Akka Actors with Java 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
let's start without further although I'm gonna show you some basics around ARCA actors and I'm gonna show you some of the new eight the ice that we introduced in in ARCA for Java 8 specifically I will start with introducing myself so my name is u1 and Riaan and I'm a developer out of Stockholm Sweden I work for a light band in the in the akka core team before joining Lichtman I worked on consulting and mentoring around Scala and akka and play framework and before that I have quite a bit of experience on the Java platform so that is about me before I start talking about specifically I'm going to talk a bit about the background or what I see as some very good reasons that akka is useful and maybe also some of the reasons that I came into existence since the dawn of computers the processors clock speeds has basically increased and increased and increased so every year that single-threaded program I wrote last year was faster and this was true up till the point around maybe 2005 as you can see here in this graph it done kind of leveled out so what happened at that point well we got to this point where it's not energy efficient or practical to keep making the clock cycles shorter and shorter so the processor makers then started to create CPUs with more cores of course we had this nice free lunch before where our programs just got faster and faster or we could be lazier and lazier as programmers and our programs but anyways run very swiftly but at this point we can't really get this kind of speed improvements for free anymore so we have to start writing programs using threads and just so we would have to structure our programs differently and we would have to start using threading primitives to to make use of the entire CPU world to make our CPU bound processing faster so this is one thing that has happened I would say like in in recent years even though it's not super recent another thing that has changed is that a couple of years ago then a typical kind of service setup would be that's one server and a failover maybe so we could kind of save keep running our business even even though our primary would go down and we would maybe have a couple of hundred thousand users and each of those would maybe have one computer each one device that they would access our system with so if we fast forward to today then this has kind of changed so the users will be more you will have much more users and each user might have a bunch of devices that the XS are serviced with and their expectations has also changed very much so they will maybe go to a competitor as soon as they have to wait for maybe for five seconds or their expectations of the service always being available has totally changed so I would kind of state that we we need abstractions to write applications that fulfill both the need to use a single machine better to actually make use of all those course but also to be able to build systems that can use more than one server in simple ways or in ways that are easy to reason about so back to academic is a tool kit to build concurrent and distributed applications it's not a framework which is a difference to many other technologies that are targeted at the same crowd it's less of something that tells you how to structure your system and how to build your architecture and more of a very useful tool box to pick up different tools from when you need to build a system that can scale over many course and many computers in this toolbox we have actors which is what we're going to cover today and we also have something called akka streams and we have an HTTP server and a few other nice tools it is written in in Scala but there is four for every feature there is also a job API so even though the internals are written in Scala it is possible to use all the parts from Java and in this talk we will specifically look at actors so we won't touch much of the other others in there interesting is that there is also a dotnet porta baka so if you're on the dotnet CLR you can also use a key from C sharp or the other languages I guess ok so actors actors was introduced or proposed by a guy called call Hewitt together with Peter Bishop and Richard stager in 1973 so it was a academic paper about a model for concurrent computation that uses actors at universal primitive of concurrent premutation sorry computation this was then implemented with Erlang in 1986 I think that's one of the more famous implementations of the actor model except raka and then akka was founded in 2009 so you have been doing this since 2009 that's seven years by now so it's by no means a young framework with that being said I would still claim that we're moving forward in a pretty good pace so it's also not not at all something that is stale because of having this years behind us so what is an actor an actor is a regular an instance of a regular class so you write the Reg totally regular class but there is a big difference in how you interact with it and how other objects interact with it so the only way to have communication and interact with an actor is through messages so to make an actor do something you send it a message a message is again also a totally you regular class but it has to be immutable because we will send them across a synchronous boundaries and as soon as we start doing that with mutable data you will have to synchronize them it will be back in this complicated world of threat primitives so when an actor receives a message it can do four things it can send messages to other actors it can mutate its own state it can change its behavior how it will react on following messages and it can create more actors so I think this is where we stop looking at slides and I will show you some code samples of of actors so I have prepared this Java project so first I want to show you that since like as I told you that okay is to keep another framework there is there is not like a microkernel or anything that you run your application on top of it's just a regular dependency so you pull in actor like this in your maven project and then you can decide to use it in parts of your application or in the build your entire application on it it's totally up to you okay so let's let's make simple see if I can open this that's weird okay so we're going to start with I told you that an actor can react on a message by changing its state so we're going to start with writing as an actor that does exactly that I'm gonna use some tricks here that aren't maybe what you would expect to see over the below partly because I don't spend all this writing Java but also partly to keep it short and concise and that I can show it in one screen so don't feel upset about about non idiomatic Java code here so I will start with creating a new class which is our counter and to make it an actor I'm gonna extend abstract actor which comes from arcade or tacular package actually I'm going to extend abstract logging actor by doing that we will get a logger for free so we can easily write some some output from the actor so the next thing we're going to do is to define a protocol so I told you that we communicate with actors through through messages so now we're going to define the messages or the message that this actor will accept and this is actually the place where my kind of weird habits is a good idea so it's a good idea to define your your protocol close too close to their class the actor which a protocol is for so in this case I'm going to define them inside of the actor aesthetic classes so I'm gonna define the class message and I'm just I'm not gonna let it have any any kind of data inside we're just gonna use it to trigger a counter that will increase over time okay and then I'm gonna define an initializer block so this is an example of where you might not what you might not do a regular java code but this is just like the default constructor so in this constructor block we'll call receive and receive takes something that is called a virtual function which is a scholar construct so but to build one of those we have a Java API so we're going to use something called a receive builder which is like the the Builder pattern and you have seen it a thousand times before I guess in in Java land and with this receive builder we can define cases which we will react on in the actor so in this case we're going to say match and then we're going to say every time there is a message of this class call this function or this method so we're going to define that as method handle like so and then I'm going to define this method like that in the end I also need to in the end of the Builder I need to actually build of course like so and then I said we were gonna keep a new Tait State so I'm gonna add a private integer which is the counter like so then when we get a message we're gonna increase that counter and I'm also gonna login info message just to make this a bit more interactive and nice to look at so you increased counter and then I'm going to print the value like this okay so now we have defined the protocol and the state the logic of the actor what we need now is to actually create the actor and to do that we need two things the first thing is is something called props and props is like a descriptor for this actor it will describe which class the actor is off and it will describe other properties that I'm not going to kind of touch in this webinar but it looks like this we call props don't create and then we give it the class so in our case counter dot class a very good habit is to create a factory for this because if we add constructor parameters to our actor you see yourself that this is using reflection or some tricks to instantiate and then we will have a runtime exception out of something that could be a compile time exception right so if I added a string constructor parameter to counter I could easily forget to add it's just props instance right where I actually describe how you create the actor so a good Factory a good habit is to define a props Factory and this is something that I do so often so I have defined this live templates in IntelliJ 4 it's like so so in this way I will have a place closer to the actual constructor where I where I can remember to add eventual parameters but in our case we have no parameters okay so now we have a way to create the props an actor doesn't kind of just we don't instantiate it ourselves like a regular object so this is a big difference from from a regular object we use an actor system so the actor live sick cycle will be bound to this actor system when we shot the actor system down all the actors will stop for example so I'm going to start with creating creating an instance of this actor system like so actor system dot create I can give it a name next like so and then using the system I will use actor of which takes the props and there is two two variants of it one that takes just two props and one that takes the name I will get back to the name later but it's almost always a good idea to give it the name so now I'm going to call this counter dot props factory method and then I'm going to give it a name counter so when we create an actor with this actor off we get back this single way of interacting with an actor which is called an actress okay if we look a bit that what we can do with an actor if there is is really not so many methods and the most interesting one is this tell and tell will send a message to this actor so we will create a new message here counter dot message create a new instance of it like so and then it takes the second parameter with which is who sent the message but in this case where we don't really have a sender we have a main thread and there is no logic to kind of catch any replies here so we will use actor if don't know sender lights like so ok so let's just try and round up to see it is super basic example ok so we can see that we got a log entry with the increased counter so this doesn't seem very amazing or special because you could have just made a method that could increase a counter right so what is interesting here is that this is totally safe from a concurrency concurrency point of view so we could actually do a loop like this we will create 5 threads like so or actually I could do it with a lambda and then oh that's actually let's do it like this anyways and then in each thread we will do another for loop so from each each thread we will send 5 messages and we will kick off all this right away like so so this is where a regular method would would not be safe since increasing the counter isn't atomic so it actually consists of the operation of reading the value and then adding a number to the value and then writing the value and there's also visibility things with with the Java memory remodel that would make it so that we could lose increments if we would do this with a regular method and immutable variable so now if I run this you should see that we get the counter increased to 25 in the end okay so this was a very basic sample of having mutable state inside of an actor let's move on to another sample so I also said that a way that the nectar can react them on messages is that it changes its behavior so let's make a sample that that's exactly that and I have this idea which is a alarm so we're going to create a new actor which is called alarm which extends the abstract logging actor to get some logging then we will define few protocol messages the first being activity so there was something happening there was a sensor telling us that something happened in the in the house where this alarm is installed and then we have the possibility to disable the alarm right to disable the alarm you will need a password because if we didn't have a password then the thief would be able to just turn off the alarm and when it goes off and we also want to have a message that is for enabling the alarm and that will also take the password right because we don't want one of the kids to accidentally set off turn on the alarm like so and now we will have we will need to have a preset password for the alarm so I'm gonna add some kind of constant here and then we will take it to the customer like so and then I can right away create the props factory that I told you about before and it will also take down the password pass it along to the actual constructor then we will have two behaviors so the first one you're not sure about the pipe yet the first one will be when the alarm is enabled and the other one is when the alarm is disabled right the actual pipe is just like I showed you before and we were setting up the initial behavior of the first sample just a partial function which goes from object to box unit which is a bit weird but this is how it looks like so and I make them final because we're going to define them and they're never going to shake and she's just going to switch between these two editors right and then I can say in the end of the of the alarm constructor that we will start with disabled right we don't want the alarm to be on and we install the alarm okay so let's define this now then so enabled is constructed using the receive builder and we will match activity and then we will call a method on activity like so and then it will get the activity as a message and I made the message empty it doesn't contain any any states so we're actually ignore ignoring it so I can just call it ignore it here let's see if I spell something weirdly yeah I'm sorry I can't spell activity like so so when we get the neck tivity then we will sound the alarm so I'm gonna use warning for this and it's gonna be really alarm alarm like so and then we have another thing that can happen when we when the alarm is enabled and that is that we get the message to disable it so I'm just gonna create another method on disable like this and this time we actually will will have some we will have some data inside of the disable message because we have that password right so we will want to check if the password we have is equal with the password in the message like so and if it is then we will get context and become so we will become disabled like so right if not also that's absolutely loving to make it clear nice alarm disabled like so and if not we will have this log warning someone who didn't know the password try to disable it like so and then in the end here we're going to do they call tilt to actually construct this receive receive block and then we're gonna do this say bold which will be receive builder dot match match is going to take only enable dot class enable like so because if there is activity when the alarm is turned off then we don't care there's not nothing gonna happen nothing's gonna happen when when the alarm is disabled except for when we try to enable it and again we're going to check if the password is correct and then we're gonna enable the same way we do I get contacts that become enabled and if the password was wrong then it's probably not that serious as the someone trying to disable the alarm with the wrong password so we're just gonna do an info someone failed to enable the enabled B alarm like so okay and then in the end here we're going to call build to complete receive so now we have created an actor that has two different behaviors and it will switch between those behaviors as a reaction to a message so let's play around a bit with it use the system to create an instance of the actor actor off with the props and we have a password and we give it a name as well alarm like so and then we catch the actor if that we get back which is actually the alarm so let's call it the alarm okay and then let's send it a few of these messages so we will start with activity to kind of show that it starts out in this disabled mode and then we're going to enable it but we're going to use the wrong password and then we will enable it with the right password then we will do some activity when the alarm is enabled then we will try to disable the alarm with the wrong password and finally we will disable the alarm with the right password and then trigger some activity okay so let's just run this and see what happens so we can see that someone failed to enable the alarm that is the first log message we get and actually there was an activity before that but since the alarm was disabled we didn't vlog anything we then an enable the alarm and then there was activity so it triggered the alarm then someone tried to disable the passed the alarm with the wrong password and Anila we disabled it and then we can see that the activity sent in the end didn't trigger the alarm okay so again this is just this is something in this context where I do it from one thread it's not very impressive maybe but the fact that we could send these messages from any thread in the entire JVM and it would be totally safe it's kind of impressive just I think that okay so let's go back to a bit of slides so I mentioned that we created the actor with a name but I didn't mention kind of what in what context that is useful or what this name is what it means so the actors are arranged in a hierarchy when we create an actor directly from the system it will live under the user Guardian which is an actor that always exists it's created by the system when it starts up we give a second parameter to this actor of method it will use that parameter as a name in this actor hierarchy inside of an actor we can call get context an actor off in this case we're creating an actor that will be a child of our actor so it will have its life cycle sort of bound to this today sector means that if we stop my actor in this case it will also stop my child so my child can never survive longer than the the parent in this hierarchy it also means something very special with regards to failure handling so I will start first with an important distinction and this distinction is Error validation errors versus failures so in a system there is validation errors which is kind of validating some input from an untrusted source this is something that will belong in the in the error handling or in the logic of a method in this actor so if it is an exception then it will be a try catch catching that illegal number format for example a failure on the other hand that is something that the actor cannot actually deal with himself so for example that could be with a database it could be a connection timed out exception so the common thing in in regular Java code would be to throw this exception outwards and you would have some business logic layer and that has no idea what to do with the connection timed out exception so it will throw it outwards and then you will have a presentation layer which totally have no idea what to do with a connection error connection failure so it will log it and show a failure page user so with ACTA we have this idea that we should instead try to send the failure somewhere where it's useful somewhere where we can actually act upon it so this is called supervision when a message comes to an actor and triggers an exception if that exception is not caught in the logic of the actor it will go to the parent of the actor and parent of the actor will have the chance to decide what should happen because of this failure and the things it can decide between is to say that the child should resume and this means that it should keep processing messages but just ignore this one because this current message was caused some something faulty another option is that it can restart the child so this is useful if the child has a state and it's possible that the state gone went invalid because of the because of the failure so this will cause the child actor to be stopped and a new instance will be started and any actor if that someone had to this actor from the from the outside will then lead to this new started actor any messages that was in the mailbox except for the one that caused a failure will be processed by this new actor so this is a really neat thing for example the database connection broke we can start a new actor which will start up a new connection if possible and will make the system sort of self heal in some circumstances there is no real there is no way to deal with the failure and the only option is to stop so this is another yet another option for the parents to deal with the exception this is for example what happens if there is of an exception thrown from the constructor by default so if it's impossible to create an instance of the actor because of an error then it won't very it isn't very likely that you can create a new instance of it and that will work ok there is one option I haven't shown on this slide which is escalate which means I don't know what to do with this I will pass it on to my parent and my parent will decide what to do but notice that in this case then that will affect the entire in the attire here a key so or a larger part of the hierarchy so in this case when the volcano erupts in the in the child if I would pass that exception upwards with escalate it would mean that the decision that the user guardian node takes four for supervision will affect the entire subtree of actors in the hierarchy okay so because of this it's important to kind of create deep ear keys rather than white hierarchies we want sections of our system that can be restarted and then will work if something goes wrong rather than something that full versus the entire system to go down okay so let's see if there was something I missed here yeah if we stop the reactor where does the active point where does message is sent to the actor go there is this special destination innaka which is called the dead letter office which is actually something that real post offices have it's a place where letters do you don't know about the recipient or the recipient doesn't exist anymore we'll go so with ARCA this means that they will be logged in the system log with some information about where they were headed but it's it's kind of useful to see when when something is wrong that that you can see what which actor isn't there anymore okay so let's play around a bit with how to actually do this in code so in sample 3 here I have prepared a little bit by creating a child that can't be trusted so in this sample it will accept messages of the type command and when it gets the command it will increase the counter and if that message is evenly divided scible by four it will throw an exception a runtime exception if it is not device level by four we will just look that we got a comment and then we have the props factory just like I told you about before and then we're gonna create this actor not from the main method of this application but instead we're going to do it from another actor so I'm actually going to change this into abstract logging actor like before to get some nice nice options for for logging and and then when it starts we're gonna do get context actor off now trustworthy child of tropes like so let's give it a nine name child awesome okay and then we're going to keep a reference to it like so and then for any incoming message we get to this supervisor we're just gonna pass it on to the child so that means that we call receive and then we use the receive builder and we match on any message and we just pass those on to child and we can do do this with a special special method so before we have used tell to send messages to actors and I will take an assembler so that the actor can reply but in this in this context we would like if the child would choose to reply to the sender we would like that to be the original sender rather than the parents so then we can use this forward method instead so we just forward this message to the child and then we pass this gift context the context of the actor and then we built so like that so now we have now we have created this hero T just like I told you about we will have this we have the user guardian like this user and then we will have this actor which we haven't really created yet but we'll create it from the main method and we have created a child so this child will have this complete path to you in this actor here okay okay and then the other thing we need to do is to define this supervision strategy which is what happens when the child throws an exception so to do this we will override a method called supervision strategy and it's supposed to return a supervision strategy and there is two basic kinds of them there is one for I'm sorry all for one which will take the decision that we we make out of the out of the exception and we will apply that to our all our children this is like the in most cases this is not what we want we want to deal with each children each child on their own sort of but we might have some kind of shared shared context of some kind some ideas that it isn't useful to keep the children alive if we have to stop one of them for example but in this case we're going to use the one for one strategy and it will take a few parameters the first one is how many retries will be done so if the actor will if we say restart button once again this many times so let's say 10 times within a specific duration then we will give up because it obviously isn't any used to to try to get this running notice here that little special thing that is easy to get wrong is that the duration is from skål about concurrent duration and it's not from the new job at a time ApS okay so we're going to say it ten times in ten seconds so so if it fails more than ten times in ten seconds then it will give up and just stop the child and then we have the final thing which is again the partial function and again we have a special builder for this innaka so we have there now I had a brain brain freeze your brain block we have the strategy builder we have the supervision strategy builder now we have the decider builder sorry and decide the builder works exactly like receive builder and it will match on a class which is an exception so in this case I showed you the norm don't trust for this child which would throw a runtime exception so we will match on this runtime exception here and then when we get this exception we have the chance to kind of look closer at it maybe look at the message or some specific flags inside of the exception but in this case we're just going to return a something called the directive to say that we want to restart or that we want to start very soon and to get access to those I'm just gonna use a shortcut here strategies so I'm gonna do a static import of strategies that lives inside of this supervisor strategy class and now we will have access to pursue I start stop and Escalade just like I described so let's start with restart here and see how this works out and then in the end need to actually build the yeah decider like so in this case also we are actually not actually not changing anything or depending on anything in the inside of the actor sure we could have defined this strategy as a static field to avoid creating a new one every time so I'm just gonna I'm just gonna do that and extract constant like so so now every instance we would create that the supervisor will have the same strategy but everything is immutable here so that's not a problem okay so final piece of the puzzle is to actually create an instance of the supervisor and run it so we do a system actor of supervisor and I didn't create the props factory sorry so I'll just sneak that in here like so supervisor dot props so and then I will capture that in a variable called provider and then we will create a for loop sending it bunch of messages like so supervisor not tell to send it the message and now the actual protocol was defined in the in the not trustworthy child so it will be a new non trustworthy child not command like so and again we have no sender here in the main thread so we just pass this act the rest of no son okay so let's run this and see what happens so we can see that the child's dog studied got a command got a command got a command and then we reached a number that is evenly divided by four so I will throw an exception and this error is actually logged by the final supervisor so if we look in the in the actual in the non trustworthy child it doesn't log anything it's just throwing an exception and what happens then we all of a sudden have a new instance running here non-trust or a child which will log three commands and then it's evenly device' built by three so how can we make this a bit more clear I will add this counter here so we can actually see that it will reset okay so let's run it again and you can see that we've got command one come on to comment three and then it got the fourth one and then after it should restart we have a new a new non-trust for each child so it will start at one again so the state has been reset let's see what happens if we instead use resume okay so we can see that we get the message of the exception is log as a worn instead of an error which restored the exception was but then it will continue and it has its state kept so we will continue from five and and six and seven and then it's evenly divided scible by four again and then we will continue upwards with the state let's try also then the stop strategy so this will make the first exception that happens the actor will be stopped and again we get an error log because this is something fairly serious and then we can see that the following messages they will go to what I talked about before did that letter q so we can see that it was intended to go to users supervisor child but there was no such child and is that it went to the dead letter Q okay if we do escalate which is the fourth one then just to be complete we can see how it's even the message that was intended sorry what I didn't mention is that there is a default strategy installed so if we don't define it then essentially any exception in the constructor will stop the actor the child and any other exception that happens when the actor is processing a message will need to restart so in this case we will get the supervisor restarted so let's go back to slides how is this actually happening them well every actor has got a mailbox which is kind of a queue so when you send it a message that will be include on to that queue and that will lead to the actor being scheduled on something called a dispatcher and its dispatcher is essentially a thread pool or an executor service from the Java concurrent vibrissae libraries the actual actors are sort of decoupled from threads so when an actor is not processing a message it will not occupy a thread when an actor gets a message we will link you itself on the dispatcher and at some point the executors will have a thread free and that will let the actor execute process that message this means that the actor isn't tied to a specific thread but it can run on any of the threads on the batcher the default dispatcher uses for queuing pool which means that for which is optimized for for messages or for processing that isn't blocking so that is something really important to understand about akka that it's if you want to do blocking then the default thread pool is built for short CPU bound jobs if you put stuff that will actually wait for a network call or file system right then then that thread will be occupied with this even though it's not actually doing anything right so there's orders of magnitude in difference between processing something in memory and waiting for something that comes over the network and if we have a few threads and we expect these jobs to be very short and we let these the actors then do something very very long and blocking then that will lead to other actors not being left to run or process their messages so a very important thing if you use akka is to understand what is blocking and what is not and isolate blocking on to its own dispatcher so this is going to be my final sample I say that I'm already a bit over time but I will quickly show it so this time I'm not going to code but I'm going to show you so this kind of ties together a few different things I have been talking about but I'm gonna just focus in on this blocking part so I have created a class that kind of simulates me a synchronous database connection so like JDBC you issue a query and it will block the thread until the database server has replied so it doesn't actually process it's just it's just blocked by waiting for for data coming back over the socket so this is simulated by a thread not sleep here so thread not sleep is very it looks very much like a a blocking operation because it will actually not really do anything with the thread but it will occupy the threads until if this time is passed so what we do to kind of isolate this is that we in akka in our application configuration of this application so I haven't covered this before but there is a built-in library in actor that will pick up configuration for your application in a specific format that looks a bit like JSON it's called a Cho see um I think so in this configuration file we have defined a blocking dispatcher so a separate thread pool essentially which we configure to have a specific number of threads and which we then when we have a blocking actor isolate that actor onto by creating the props but then saying with dispatcher this is the name of the dispatcher that we defined in the configuration file so this way there will be a separate thread pool for those blocking actors and the other actors can churn along processing messages without problems even though the database thread pool is blocked even though all those threads are being blocked there the other actors can do stuff which they want okay I'm not going to look more I think get this last sample so I guess you can maybe take a look at it on your own there will be a link in the end so some repetition of some do's and don'ts that I may be mentioned and some stuff I haven't mentioned don't put everything in a flat tire key but make this kind of deeper here keys and push dangerous work downwards because that is how you can make smaller parts fail independently and have them recover from failure make sure that you isolate blocking so that you don't affect actors that that don't do blocking at all with their with the blocking actors so a good example would be you're writing a web application and you have some actors that will call it relational database and then you have some actors that actually have all their data in memory already and they can just reply to the requests very quickly so if you would run all of these sectors on the same thread pool then the blocking ones would stop the first one from executing as well but if you isolate them then the first one will be able to serve requests even though the slow ones are overwhelmed with slow requests don't write all your logic inside your actors and don't build don't write all your logic inside the the lambdas that you can give to this receive builder and decider builder but instead push it outwards sort of best case make it regular logic like you would always write in Java and then use that inside of actors to kind of organize them with synchronous boundaries and allow them to run concurrently make sure that all messages are immutable or you will have problems with different actors not seeing stuff that you changed in the message because of how their Java memory model that works and that the actors can run on any of these threads that you have on the dispatcher in the executor service of dispatcher although everything with with actors because it doesn't really make sense all the time to recruit asynchronous boundaries between things just do it where it's actually useful and this is something you can probably now drawn on a whiteboard and think about what things can happen in parallel and what what things cannot happen in parallel so for example as a Enterprise Java developer your first kind of architectural tool would maybe be the three-tier architecture where you have the presentation and then the business logic and then the database and it's maybe not so useful to use these tears as abstractions or places where you would put the asynchronous boundaries maybe around the database because you will have 10 database connections that you need to share between different parts of the system but maybe the actual logic for rendering the response parsing the request and processing business logic belong in the same kind of asynchronous island the same actor who knows ok so in addition to what I have told you about there's two big things in a kadai I think needs the service mentioned and the first thing is like a cluster and given that actors are ill things that communicate just through messages it's a perfect abstraction to also scale out so you will you will be able to put those actors on different nodes and they will still communicate through messages so the the way they communicate will be the same the abstraction will be the same of course there will be differences for example you need to handle that the latency and response times are very different on a local node compared to the remote node but this is a really nice kind of I would almost say the killer app of akka another thing is extremes which is a synchronous and back pressured streams framework for building streaming graphs for processing data of different kinds and this is also kind of the core of the HTTP server which is has been written for akka okay so if if you after this long and tedious babbling from me feel like this is something you would like to look closer at then we have some pretty extensive talks that might be interesting to start with and that is you can find that I use slash dogs we have a very friendly community with a killer Channel and the mailing list which are really good places to ask questions and get help and this live coding sources will be available shortly after the webinar at this github repository listed ok so I think that would be time for maybe questions done yeah thank you join for comprehensive introduction it was really interesting and yeah we are slightly ran out of time but still have quite still have time for some questions I'll read them and yeah so you can answer the first question is there a way to create an actor without having to extend the abstract actor no so this is why I mentioned that you should model your domain specific things with your regular kind of object-oriented toolkits and wrap those with actors rather than maybe tightly coupled the logic to the actors ok thanks and the next question I try to implement an actor in Scala I find it's easy just to override receive method and pass methods to cube by using the exclamation mark however in Java it's a little complicated to write and understand please let us know your view on that yeah okay so Scala gives us a few more tools to make the API is to interact with actors minimal in a very concise which isn't possible with Java on the other hand with Java everything is very explicit and could probably be easier to follow and I mean it's a it's a matter of taste with languages so I think it would be hard to make it more minimal api's for job and then they currently are of course there are cases corner cases some sort of edges but but in general I it is just a bit more verbose in Java and that might be something you like or it might be something that you don't like so you have the choice between Java and Scala and Watauga okay and the next question what is the scope of an actor system how to access an egg an actor of an actor system from another Jairam process so if you want to interact between systems of different JVMs there are a few options so one option is when you want to build a distributed system right you want to build something that is one application that covers more than a single JVM and in this case it is clustering which I mentioned clustering and like I can remote thing was definitely clustering in the other case it's just two systems that are interacting through some whatever protocol you would like so for example you would write maybe a mail client and a mail server then you will communicate through an application-specific protocol rather than doing something that is akka specific even though you might write both sides of the communication part in in there in that with an actor system okay moving to next question the question is about the first sample so basically the sample app shows that the messages will be processed in some kind of queue right meaning that each message will be processed until it finished and then the actor will process the next message is it correct understanding yes this is exactly correct so there is a single threaded illusion inside of the actor even though it might move between the threads of the of the dispatcher it's when you look at it they will seem to be running in a single thread one message at a time yeah and next question is it is it recommended to access is it advisable to access the database from an actor shouldn't it shouldn't all the actions performed by an actor be a synchronous so this is exactly what I was talking about in the end you can do blocking stuff in actors but you need to make sure that you isolate them onto a specific thread pool based dispatcher so that they don't affect the rest of the system but I mean if you are allowed to have 8 connections to your database then it doesn't doesn't matter if you have you know you could represent that with 8 actors and it will fit perfectly with what you can actually do in your system ok and next question we have a built-in actor system and play framework my question is while creating actors shall we use the default one or create our own actor system and is it useful to create more than one actor system ok so my my my current knowledge of play is a bit rusty but there used to be a separate kind of actor system for play and one for kind of the user application I'm not sure if it is like this anymore so this was probably because at some point they wanted to make they were isolated from the user logic very unsure if it's still like this in some cases it might be useful to create more than one but in general normal application wouldn't want wouldn't need more than one and the reason for this is that each actor system will occupy resources and they will create thread pools and so it's a relatively heavy construct you wouldn't want lots and lots of it and next question is it is it possible to use akka in g:w application server I have heard about people doing this so the tricky part is that the thread pool that akka manages how that kind of if the Java EE application server allows things to have their own threads I think it's a bit vendor dependent like in general which are way you're not allowed to start threads but you could probably with vendor specific extensions create something that will create an actor system that you can then use as a resource inside of your application server so it depends okay and now a question whether it possible to inject a spring bean to an actor yeah it requires some special some special hoops but there is examples in the documentation even I think for integrating with spring okay now if you have a huge number of factors how the actor system creates them in parallel when do you know when this when the system is ready to handle messages if the actors are dependent on each other okay so you can see you can think of this question in different ways one way is that if you have the actor if it's perfectly valid to send it messages even though it's not ready so those will just be queued up and then when the actor is actually started so that's happening as synchronously then you call actor off it was and it returns it doesn't mean that the actor has be started already just means that but you will get the nectar of which you can send messages to so if you have a huge and complex kind of graph which you need to get in some specific state before you can start have it start processing messages then you need to signal that somehow so in your entry points you will have have to have some kind of protocol which you get from all these things that needs to be started and initialized so in general I would say try to use like dependency injection in in the form of not in the form of a framework but in the form of if an actor needs to talk to another actor pass the actor ref to it this way you will essentially have to create the actors in an order that matches the dependencies and you will not have to kind of keep any kind of protocol to synchronize this you will you will essentially be able to start as soon as you have created all of the actors okay moving put it could you recommend any books about akka not from the top of my head but there is a bunch and there is a list in the documentation that I would recommend you to look at okay the question is there way to have tell and forward methods when actor rafts be typesafe there is a comment next to the question probably not because they accepted types of messages where an actor can change over time yeah so this is definitely kind of part of the problem why it's really hard that the behavior can change but also like one of the really neat things with actresses that you can just put another actor in between you keep the protocol you're the sending actor doesn't know anything about it but you just snuck in this cashing actor in between which will respond to some messages but not others this is also something that is hard to represent you know typesafe matter however there is a sub-module of actor which which is being under development which is called akka typed which if it's kind of it's not ready anytime soon but there is work being done on on a year and a way to do typesafe actors I'm not sure if this will be possible to represent with with Java API so in the future we will see where it kind of lands that is something to look into if you're interested in this topic yeah and knowing next question not really sure I get the meaning of the question still I'll read that any blocking routine has to be placed in a different thread pool so as always with software it depends but it's a good rule of thumb that you should try to isolate the blocking stuff onto a separate thread pool of course you can have a separate thread pool for all the i/o for example all the blocking i/o even though you have different actors doing different blocking i/o so this is kind of a something you have to think about with your own system how it will affect it which parts will stop other from processing and if that's sensible or not yep now you mentioned better deep here our kiss then white hair our keys is it just because there's a supervision or something else yeah absolutely about supervision that you can separate parts of your system that shouldn't kind of affect the other parts when they break and you push the dangerous work downwards in hierarchy right because because the error comes upwards and the smaller parts you have that will fail the the smaller parts you can restart without affecting other parts of the system okay in the current version of our con is it considerate a good practice to use our core futures and the patterns ask parenting okay so in the current version of vodka which is to 4.10 from Java then you will probably not use future so much but instead the completion stage class which is essentially the same thing as futures futures is a data structure from from Scala and the completion stage is something that does the same on the Java side the ask pattern I didn't really mention during the talk but it's it's a way to encapsulate a query so if you have a protocol which contains a query message and then a response message and you want to kind of tie those together somehow with a timeout because you don't want to wait infinitely for response and then you want to kind of act on the response if you're outside of an actor I need to query it then definitely there is this isn't really another option then ask if you're inside of an actor there are a few different options but parents the task is pretty good note however this is a special special patterns don't ask for Java 8 which is called CS patterns don't ask I think which will return on a completion stage and you will not have to kind of 12 into Scala the ice to do stuff from Java okay next question how does actor how does act integrate with message and cues like RabbitMQ with this advisable so there is open source project connector that connects to rabbitmq with with actors so you will get messages from the mq like messages inside of your actor system it's very nice I have used it before I joined my spotlight band there might it might be a better fit to look at extremes with extremes connectors because they kind of match how a message queue work a bit better let you kind of back pressure and not consume too many messages from the message queue compared to how many you can process and your throughput ok and written next question I'll be working on the custom akka system which has some unknown who now flows what we could observe was that some actors crashed and we lost their state what are the first parts we should check ok so if if there are actors that crash and then they will get restarted because that's the default supervision strategy so that is look at their parent actor and how it will supervise its children think about if you should have different behavior or if if you can push the dangerous thing that caused them to crash lower down in the hierarchy okay good is it possible to communicate across VM or host yeah this is again depends on what you want to do if you want to build a distributed system new you will use akka cluster or accurate mooting I would say akka cluster if you want to build for example client-server system of some kind then it will just be about defining a protocol to use over TCP for example so then either side won't really know that the other side is it's an actor system but it will be like a separate client and server implementation yeah [Music] next question do you plan to create webinar about ARCA classroom so I think this might be a question to you a bit maybe yeah sure why not yeah sure do actor support reactive spec that is back pressure enabled so I'm gonna guess that with reactive spec what this meant is reactive stream specifications so this is what our cast reims is it's an implementation of the reactive stream specification actors in themselves doesn't do back pressure so you will have to define define your actor system to to deal with if you have a slower slower throughput then you have an inflow of messages for example you will have to think about this when you design your actors yep and when and why to go for arc route routing can you elaborate its significance in a simple way yeah so what I didn't look closer at in the fine sample of the the LiveCode or the the prepared sample of the life coat was that I was actually using routing so what routing is is something where you can create four instances of an actor for example and you will essentially have an actor F to send messages to you don't you are kind of deferred how messages are distributed between those four actors so there's different different kind of routing for example you could have done a round round-robin router which will for every new message that comes in it will just pick the next actors and then and then when it reaches the end of the list they will start over start over with the first one so this is for example a way to distribute processing over all your course you create as many actors as you have course and then you just use this router to to distribute the work between the menus and the messages okay good I think that's that's it we have no more questions but in case someone has more questions just feel free to ask them in Twitter were when we publish the recording you can post them as comments so we'll try to answer all them so thank you for your time and for questions and John of course thank you for the presentation thank you okay see everyone take care and have a good day good bye bye bye
Info
Channel: IntelliJ IDEA by JetBrains
Views: 7,464
Rating: 4.7192984 out of 5
Keywords: IntelliJ IDEA, Akka, Java, Java 8, Lightbend
Id: 7phNrU8DyWA
Channel Id: undefined
Length: 83min 50sec (5030 seconds)
Published: Mon Sep 19 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.