Behavioral Programming in Clojure

Behavioral programming is a relatively new programming paradigm pioneered by David Harel, the creator statecharts. It has very solid theoretical foundations, and lends itself to formal proofs. But it also is intended to express software in a more intuitive, “human” way.

The bthread is the main abstraction. It is an isolated unit of behavior that has no direct knowledge of any other bthread. Instead, it receives events, and it can request, block, or wait on other events. Waits can be used to park b-threads.

Bthreads are composed into an application that manages incoming events, notifying parked bthreads. Bthreads are cheap, and need not map onto real threads.

Harel, Marron, and Weiss describe behavioral programming as follows:

We propose the term behavioral application for software consisting of independent components (called b-threads) that generate a flow of events via an enhanced publish/subscribe protocol, as follows. Each b-thread is a procedure that runs in parallel to the other b-threads. When a b-thread reaches a point that requires synchronization, it waits until all other b-threads reach synchronization points in their own flow. At synchronization points, each b-thread specifies three sets of events: requested events: the thread proposes that these be considered for triggering, and asks to be notified when any of them occurs; waited-for events: the thread does not request these, but asks to be notified when any of them is triggered; and blocked events: the thread currently forbids triggering any of these events.

Behavioral Programming in Clojure

As far as I know, there is no open source behavioral programming library in Clojure.

I’ve written an article here making the case that Clojure and behavioral programming are perfectly suited for each other. While the Java implementation takes a very imperative approach, it is possible – and natural – to implement behavioral programming declaratively, leveraging Clojure’s idiom. (This is especially true of sequence idioms.)

Eugenni Shevchenko recently authored a very nice article showing how bthreads can be implemented on top of core.async. I would recommend it as well.

Further reading

Two articles I would recommend as entrypoints to the concepts of behavioral programming are:

Concluding Thoughts

I think there is a huge amount of potential in combining behavioral programming and Clojure to write much more understandable and maintainable event driven systems – from UIs to stream processing. What do you think?

2 Likes

Thanks for your post! :blush: It gave me some ideas.