Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Try unsynchronized deftype #3

Closed
RokLenarcic opened this issue Dec 13, 2022 · 1 comment
Closed

Try unsynchronized deftype #3

RokLenarcic opened this issue Dec 13, 2022 · 1 comment

Comments

@RokLenarcic
Copy link

I've noticed this:

Mutation

The first use of a transitive accumulator stored it in a Atom, which are threadsafe mutable values. However, these parsers do not communicate between multiple threads, so a less safe type of mutation can be adopted. Clojure's Volatile values are similar to Atoms, but without the thread safety guarantees. On the JVM they are still built with Java volatile values, which force memory synchronization. This is an unnecessary cost when the values are isolated to the stack of a single-threaded process, but without providing host-based extentions then this can't really be avoided. (Perhaps a hosted array could be used as a mutable object - I have yet to test and compare this to a volatile).

You can use deftype to have a type where fields are not volatile or at all synchronized. From the doc:

Fields can be qualified
  with the metadata :volatile-mutable true or :unsynchronized-mutable
  true, at which point (set! afield aval) will be supported in method
  bodies.

It would also be easy to just use a java class directly that is used just for this purpose.

@quoll
Copy link
Owner

quoll commented Feb 19, 2023

I'm happy with the way it works right now for a few reasons:

  • Because it's a value bound to a dynamic var, it's actually thread-safe (since rebinding is done with TLS)
  • It uses built-in types with well-known Clojure idioms
  • Despite my comments, I feel uncomfortable creating mutable objects like this without good metrics to indicate a performance problem that should be addressed.

Also, I have always preferred an array for a single mutable value, as these already exist. If I needed more semantics on the data or multiple mutable values, then a deftype would be more appealing.

@quoll quoll closed this as completed Feb 19, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants