HEY!!! I am back with Actors, one of the GPars interesting features.
I will start with Actor
Actor is such an Entity which allows only one thread at a time, irrepective of the object the thread belongs!!!!
Lets start with a simple exemplar.
We have send messages to the Actor from the main thread thrice , but all these messages are being processed sequentially by the Actor in a Separate thread, and the main Thread thus quits, because all these Threads that execute the job inside the actor are Daemon threads, so in order to make the programme excute (as we have introduced delay here), we have joined the actor in the end as:
We have also intrduced delay inside the Actor to show that, while a thread is sleeping, other threads, that has been started from the main thread, do not get the chance to execute, until and unless the current thread finishes its execution.
Actor has another propitious utility i.e. reply, which we have commented out here. Please check the GPars for furthur details.
We can execute the Tasks inside Actor by Non-Daemon Threads, by using Non-Daemon thread pool.
The Output of the above code will be:
Lets track another Actor example
DefaultActor contains some Lifecycle methods Like:
1) afterStart() -> Gets invoked after the Actor is started explitly using the start() method.
2) act() -> This method reacts to the incoming messages.
The above example depicts different aspects of actors, but the significant one is, how an actor replies to the messages sent by another Actor.
In the above example there are Actors with names Act1, Act2 and endActor
In the main method we have initiated Act2 and started it and made the main Thread to wait until the endActor has finished execution
After we have started Act2, from within the afterStart() method we have started Act1.
Now the Act2 actor sends messages to Act1 actor and which reacts accordingly to the messages of Act2 by sending appropiate replies, which the Act2 processes and on termination endActor is invoked.
Another important point is if there is no loop inside an Actor then it can react to only the first message send to the actor. Besides , an Actor has a handful of built in variables like sender, which denotes the sender of messages and etc.
This is in Short about actor.
Actor is such an Entity which allows only one thread at a time, irrepective of the object the thread belongs!!!!
Lets start with a simple exemplar.
import groovyx.gpars.actor.Actor
import groovyx.gpars.actor.Actors
import java.util.concurrent.TimeUnit
class ActorTest {
static def msg11="Default"
static def startTime;
/**
* Ac Actor is initiated as Actors.actor{...
*
*/
static def actor = Actors.actor{
println " Actor Initialized by:${Thread.currentThread().getName()}"
println "The metaclass is: ${delegate.getClass()}"
/**
* The Delegate inside Actors.actor Closure is Default Actor
*
*/
loop{
println "Inside Actor Loop :${Thread.currentThread().getName()}"
react(20000) {msg2 ->println "The Msg-3 is $msg2 :${Thread.currentThread().getName()}"
if (msg2 == Actor.TIMEOUT) {
//continue conversation
println "Thank you for $msg2 I am terminating Myself as Time Difference is ${new Date().getTime() - startTime}"
terminate()
}
msg2 = msg2+msg2
msg11 = msg2 + ' Subha '
//reply "Received!!!!"
//println "Sleeping Start.....The Current Thread is (Actor-33):${Thread.currentThread().getName()}"
Thread.sleep(8000)
msg11 += ' Paul '
//println "Sleeping End....."
}
println "Exiting Actor Loop :${Thread.currentThread().getName()}"
}
}
static mains (args)
{
startTime=new Date().getTime()
TimeUnit.MILLISECONDS.sleep(4000)
15.times {print "*"
}
println ''
println "The Main Thread.... Before Sending 1: ${Thread.currentThread().getName()}"
def a = actor.send "1"
println "The Main Thread.... Before Sending 11: ${Thread.currentThread().getName()}"
def b = actor.send "11"
15.times {print "*"
}
println ''
println "The Main Thread.... Before Sending 111: ${Thread.currentThread().getName()}"
TimeUnit.MILLISECONDS.sleep(15000)
def c = actor.send "111"
println "..... Sleep Finished...."
//Thread.sleep(10000)
[actor]*.join()
println "The msg is $msg11"
}
}
The main consideration behind the above mentioned code block is to exhibit that at a time only One thread can enter the critical area inside the Actor.We have send messages to the Actor from the main thread thrice , but all these messages are being processed sequentially by the Actor in a Separate thread, and the main Thread thus quits, because all these Threads that execute the job inside the actor are Daemon threads, so in order to make the programme excute (as we have introduced delay here), we have joined the actor in the end as:
[actor]*.join()This will make the Main Thread to waitfor the Actor(s) to finish, but as we have introduced loop inside the Actor, the actor will keep on running until we manually terminate the Actor, so in order to do that, we have used react() [N.B. Th reach() is the method which reacts or we can say responds to the messages being sent to the Actor] with a Timeout, which will make the actor wait for 20000 ms max for another message to arrive, and if there has been no message within that timeframe, then a Actor.TIMEOUT will be thrown and the Actor will terminate and thus terminating main.
We have also intrduced delay inside the Actor to show that, while a thread is sleeping, other threads, that has been started from the main thread, do not get the chance to execute, until and unless the current thread finishes its execution.
Actor has another propitious utility i.e. reply, which we have commented out here. Please check the GPars for furthur details.
We can execute the Tasks inside Actor by Non-Daemon Threads, by using Non-Daemon thread pool.
The Output of the above code will be:
Actor Initialized by:Actor Thread 1 The metaclass is: class groovyx.gpars.actor.DefaultActor Inside Actor Loop :Actor Thread 1 Exiting Actor Loop :Actor Thread 1 *************** The Main Thread.... Before Sending 1: main The Main Thread.... Before Sending 11: main The Msg-3 is 1 :Actor Thread 1 *************** The Main Thread.... Before Sending 111: main Inside Actor Loop :Actor Thread 1 Exiting Actor Loop :Actor Thread 1 The Msg-3 is 11 :Actor Thread 1 ..... Sleep Finished.... Inside Actor Loop :Actor Thread 1 Exiting Actor Loop :Actor Thread 1 The Msg-3 is 111 :Actor Thread 1 Inside Actor Loop :Actor Thread 1 Exiting Actor Loop :Actor Thread 1 The Msg-3 is TIMEOUT :Actor Thread 1 Thank you for TIMEOUT I am terminating Myself as Time Difference is 48077 The msg is 111111 Subha PaulThe above outputs are being printed with some deplay, and which is interesting..
Lets track another Actor example
import groovyx.gpars.actor.DefaultActor;
import groovyx.gpars.actor.Actors;
class ActorTest2 {
class Act1 extends DefaultActor
{
def secretNum
void afterStart() {
println " ***** After Start is invoked ***** "
secretNum = new Random().nextInt(10)
println " ***** After Start is invoked done***** "
}
void act() {
println "**** Act is Invoked **** "
loop {
println "**** Loop is Invoked **** "
react { int num ->
println "**** Reaction Started for $num **** "
if(num == 10){
reply 'you win'
terminate()
}
else if (num > secretNum)
reply 'too large'
else if (num < secretNum)
reply 'too small'
else{
reply 'you win'
println "Terminating Myself....."
terminate()
println "Terminated....."
}
println "**** Reaction Finished for $num **** "
}
println "**** Loop is Finished **** "
}
}
}
class Act2 extends DefaultActor
{
String name = 'Subha'
Act1 server = new Act1()
int myNum
void afterStart() {
println " ***** After Start is invoked for Act2 ***** "
server.start()
println " ***** After Start is invoked done for Act2 ***** "
}
void act() {
loop {
myNum = new Random().nextInt(10)
server.send myNum
react {
println "The Sender is: $sender"
switch (it) {
case 'too large': println "$name: $myNum was too large"; break
case 'too small': println "$name: $myNum was too small"; break
case 'you win': println "$name: I won $myNum"; endActor.send server ; terminate(); break
}
}
}
}
}
static def endActor = Actors.actor{
//loop{
react{ server1 ->
println "%%%%%% End Actor is invoked %%%%%%"
server1.stop()
// terminate()
println "%%%%%% All Terminated %%%%%%"
}
//}
}
static def testActor = Actors.actor{
react { obj ->
println "The Object is $obj"
}
}
static def loopTestActor = Actors.actor{
def counter =1
loop{
println "Entering Loop.......... $counter"
react { obj ->
println "The Object is $obj"
}
println "Ending Loop.......... ${counter++}"
}
}
/**
* Usually the react method accepts a single Msg
* Now in order to make it accept more than one i/p
* parameter, we need to nest react
*
*/
static def calculator = Actors.actor{
react{ a ->
println "The First input is: $a Thread-${Thread.currentThread()}"
react{ b ->
println "The second input is: $b Thread-${Thread.currentThread()}"
console.send(a+b)
}
}
}
static def console = Actors.actor{
react{result ->
println "The result of addition is: $result Thread-${Thread.currentThread()}"
}
}
static main(args)
{
//def act1 = new ActorTest2.Act1(new ActorTest2())
//def act1 = ActorTest2.Act1.newInstance(new ActorTest2())
def act2 = ActorTest2.Act2.newInstance(new ActorTest2())
act2.start()
[endActor]*.join()
testActor << "Okkkiii----9"
testActor << "Nexttt-Okkk"
testActor.join()
20.times {
print "="
}
println ""
loopTestActor << "Okkkiii"
loopTestActor << "Nexttt-Okkk"
loopTestActor.join()
println "============End In Main Join............."
calculator.send 5
calculator.send 9
calculator.join()
}
}
As in the previous example we have initialized Actor with Actors.actor {...., here we have extended DefaultActor and created an Inner class for the Actor.DefaultActor contains some Lifecycle methods Like:
1) afterStart() -> Gets invoked after the Actor is started explitly using the start() method.
2) act() -> This method reacts to the incoming messages.
The above example depicts different aspects of actors, but the significant one is, how an actor replies to the messages sent by another Actor.
In the above example there are Actors with names Act1, Act2 and endActor
In the main method we have initiated Act2 and started it and made the main Thread to wait until the endActor has finished execution
After we have started Act2, from within the afterStart() method we have started Act1.
Now the Act2 actor sends messages to Act1 actor and which reacts accordingly to the messages of Act2 by sending appropiate replies, which the Act2 processes and on termination endActor is invoked.
Another important point is if there is no loop inside an Actor then it can react to only the first message send to the actor. Besides , an Actor has a handful of built in variables like sender, which denotes the sender of messages and etc.
This is in Short about actor.

No comments:
Post a Comment