yazz.com
yazz.com

Reputation: 58796

How can I tell if a ref is being updated by a dosync in Clojure?

I have some updates which need to be made to a ref, but I want to choose a time to perform the updates when the ref is not in heavy use. Is there a way I can programatically tell when the ref is in a transaction?

Upvotes: 3

Views: 163

Answers (3)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91587

you could add-watch that would update an access-time each time your ref is written (you mentions it was write mostly). This would give you a huristic for busy.

(def my-ref (ref {}))
(def my-ref-atime (atom 0))
(add-watch my-ref (fn [key ref old new] (swap! my-ref-atime current-time-fn)))) 

then only do low priority work when atime is more than 10ms in the past.

Upvotes: 4

Stuart Dabbs Halloway
Stuart Dabbs Halloway

Reputation: 1666

You may be asking a single identity to do too much. Consider having two identities: one that has high write volume, and another (possibly derivative) identity that is updated occasionally.

Your approach already implies that the occasional updates aren't part of the ref's timeline, since you are willing to defer them.

Upvotes: 4

dbyrne
dbyrne

Reputation: 61081

Are you sure you want to use a ref and not an agent?

It sounds to me like you want to perform updates, but you don't care about when the updates actually happen (just so long as they happen eventually). This is exactly what agents are used for: sharing state in an asynchronous and independent manner. Refs are for sharing state in a synchronous and coordinated manner.

Structuring application logic around whether or not a ref is in a transaction sounds like a bad idea to me. Maybe if you provide more details someone can come up with a better design.

Upvotes: 1

Related Questions