#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2010
    Posts
    68
    Rep Power
    5

    Using an Actor Model for a Server


    Whenever I try writing servers or multithreaded programs, I've always had a hard time. I guess this happens due to how awkward it is for me to write how a client will handle data and then do the same for a server. It would feel more natural to write both at the same time as if everything was a contiguous, singlethreaded program, which of course wouldn't be the case.

    To make things easier, I'm using an actor model (I think). Here's what I've set up

    Code:
    public interface Message {
        public void sendTo(Actor actor);
    }
    
    public class Actor {
        public void send(Message message) {
            message.sendTo(this);
        }
    }
    My idea was that the Actor class would be extended for whatever purpose and also given methods (or variables) for messages to use to alert or change the state of the actor.
    An implementation might look like this

    Code:
    class MyActor extends Actor {
        private String data;
        
        void print() {
            System.out.println("I was sent " + data);
        }
        
        static class MyMessage implements Message {
            public final String dataToSend;
            
            MyMessage(String dataToSend) {
                this.dataToSend = dataToSend;
            }
            
            public void sendTo(Actor actor) {
                if (actor instanceof MyActor) {
                    MyActor myactor = (MyActor)actor;
                    myactor.data = dataToSend;
                }
            }
        }
    }
    
    class Implementation {
        public static void main(String[] args) {
            MyActor myactor = new MyActor();
            myactor.send(new MyActor.MyMessage("Hello World!"));
            myactor.print();
        }
    }
    Of course, a message doesn't necessarily have to be a subclass of the actor which it operates on. I just did it so everything could be a bit more encapsulated.

    To my understanding (for my implementation), messages define how actors can operate, and actors are just data. This works well for a server/client set up since you can write messages and then send them via socket thus achieving the desired action.

    I'm not worrying about multithreading which makes what I have quite different from what an Actor Model should be. Am I trying to emulate some other programming style (other than an Actor Model) on top of Java's OOP? Is what I'm trying to do worth trying? Or should I just use some Actor library with Java?
    Last edited by JonthnC; January 24th, 2013 at 09:01 PM.

IMN logo majestic logo threadwatch logo seochat tools logo