HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Review of simple Java Actor library

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
actorsimplejavalibraryreview

Problem

How can I improve this code?

Also available from git://github.com/edescourtis/actor.git .

Actor.java

package com.benbria.actor;

public interface Actor extends Runnable {
    public abstract void send(T msg) throws InterruptedException;
    public abstract void stop() throws InterruptedException;
}


ActorListener.java

package com.benbria.actor;

public interface ActorListener {
    void start(Actor actor);
    void stop(Actor actor);
    void exception(Actor actor, Exception ex);   
}


Behaviour.java

package com.benbria.actor;

public interface Behaviour {
    void receive(Actor self, T msg);
}


ThreadActor.java

```
package com.benbria.actor;

import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

import com.benbria.actor.listeners.NullActorListener;

/**
* @author Eric des Courtis
*
*/

public final class ThreadActor implements Runnable, Actor {
private final BlockingQueue> queue;
private final Behaviour behaviour;
private final ActorListener listener;

public static Actor create(Behaviour behaviour, ActorListener listener) {
return new ThreadActor(behaviour, listener);
}

public static Actor create(Behaviour behaviour) {
return create(behaviour, new NullActorListener());
}

public static Actor spawn(Behaviour behaviour, ActorListener listener){
Actor a = create(behaviour, listener);
new Thread(a).start();
return a;
}

public static Actor spawn(Behaviour behaviour) {
return spawn(behaviour, new NullActorListener());
}

public static Actor createWithPriorityQueue(Behaviour behaviour, ActorListener listener, final Comparator comparator) {
return new ThreadActor(behaviour, listener, new PriorityBlockingQueue>(10, new Comparator>() {
@Override
public int compare(StopOrT o1, StopOrT o2) {

Solution

-
No need for Actor to extend Runnable

-
NullActorListener is redundant: MultiplexedActorListener with empty list of listeners behaves the same way. Having MultiplexedActorListener as a default listener, no need for the ThreadActor constructors with ActorListener parameters - one can just add listeners after ThreadActor creation.

-
Multiplexer is a wrong term, you meant demultiplexer, see Wikipedia

-
Parameter Actor self in Behaviour.receive() can be dropped. The case when Behaviour really needs access to its own actor is rare, and can be implemented with passing Actor to Behaviour implementation constructor.

Context

StackExchange Code Review Q#25188, answer score: 2

Revisions (0)

No revisions yet.