Akka is a concurrent processing framework based on the actor model. Based on the event-driven concurrent processing model, each actor has its own attributes and operations, thus avoiding the need to share attributes (data) between multiple threads) instead, the lock mechanism is used for processing. This mechanism is well applied in Scala and cloure languages. It puts operations and attributes in an independent unit for processing, thus improving the concurrent processing capability.
The following uses the simplest helloword as the start to enter the akka world.
Function Description:
It is very easy to send a message to another actor through one actior and return the processing result. However, asynchronous processing is not synchronous, what's amazing here is that akka's internal mechanism has been further studied.
Helloworld class
Java code
- Package com. Test. akka;
- Import akka. Actor. Props;
- Import akka. Actor. untypedactor;
- Import akka. Actor. actorref;
- Public class helloworld extends untypedactor {
- @ Override
- Public void prestart (){
- // Create the greeter actor
- Final actorref greeter =
- Getcontext (). actorof (props. Create (greeter. Class), "greeter"); // create a greeter actor instance
- // Tell it to perform the greeting
- Greeter. Tell (greeter. msg. Greet, getself (); // send a message to greeter actor through the tell Method
- }
- @ Override
- Public void onreceive (Object MSG ){
- If (MSG = greeter. msg. Done ){
- // When the greeter is done, stop this actor and with it the application
- Getcontext (). Stop (getself ());
- } Else unhandled (MSG );
- }
- }
Greeter class
Java code
- Package com. Test. akka;
- Import akka. Actor. untypedactor;
- Public class greeter extends untypedactor {
- Public static Enum MSG {
- Greet, done;
- }
- @ Override
- Public void onreceive (Object MSG ){
- If (MSG = MSG. Greet ){
- System. Out. println ("Hello world! ");
- Getsender (). Tell (msg. Done, getself ());
- } Else unhandled (MSG );
- }
- }
Run the helloworld class. akka provides a main actor class. You can use this class to directly execute the above method. In eclipse, click Open Run dailoge in the helloworld class, and then click main. enter akka in the class option. main, and then select arguments to enter COM. test. akka. helloworld, click apply, and the running result is as follows:
Java code
- Hello world!
- [Info] [10:16:33. 003] [Main-akka.actor.default-dispatcher-5] [akka: // main/user/APP-terminator] Application supervisor has terminated, shutting down
According to the running results, helloworld actor correctly calls greeter actor because it outputs Hello world! From the infor log, we can see that the helloworld actor normally receives the greeter actor and stops the current actor.
Hello akka getting started example