We have a piece of code with a static field val format = DateTimeFormatter.forPattern("yyyy-MM-dd")
Now this instance of formatter will be used by concurrent threads to parse and print date format.parseDateTime("2013-09-24")
and format.print(instant)
.
I learnt that in Scala you can write your code without caring for concurrency, provided that you only use immutable fields, but what about the performance ? Can it become a bottleneck if several threads use the same instance ?
Thanks,

- 838
- 1
- 10
- 24
-
I think there is no problem with sharing this filed defined as val. Also its prefer to put static things like this to scala object. – kisileno Sep 24 '13 at 09:42
2 Answers
Your question is more related to Java. If the implementation of the forPattern
method is thread safe you can share it between many threads without any bottleneck.
Check the javadoc to see if the implementation is thread safe. In your specific case, I will assume that you are using the JodaTime library :
extract from DateTime Javadoc :
DateTimeFormat is thread-safe and immutable, and the formatters it returns are as well.
Has a counter example see SimpleDateFormat javadoc :
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
Using a val just mean that the variable reference will not change after his declaration. see What is the difference between a var and val definition in Scala?
-
-
can you maybe add a side note on performance issue to your response, this is the second part of my question ? – Benoit Guigal Sep 24 '13 at 20:24
-
hard to answer on the performance issue because it depends on many factors. Performance is a broad subject. – evantill Sep 27 '13 at 08:19
Well looks like you have mis-interpreted it: Concurrency in Scala is very much like Java (or any other language) and nothing much special. Just that it provides alternative libraries and syntactic sugar to get them done with much lesser boiler plate and more importantly do get them done safely (ex: akka).
But the other principles like: dependency on number of cores, thread-pool sizes, context switches etc etc will all have to be handled and taken care of.
Now for the question if a immutable val
accessed by multiple threads degrades performance: I dont think there should be any over-head nor do I have data to support. But I think the performance might be good as the processor can cache it and the same object can retrieved faster in another core.

- 31,116
- 15
- 98
- 163