Re: how can i optimize the given below code
Piotr Kobzda wrote:
while (source.length() < length)
this.source = source += source;
Why are you assigning the string twice each iteration, once to the
local variable and once to the instance variable?
Piotr Kobzda wrote:
It's to let access as soon as possible the newly created string by the
other concurrently running threads.
Yes, I know, that the Java memory model do not guarantee this (field
In fact, it pretty much guarantees that for some runs, the threads will
*not* see the changes made by each other.
So what? My primary goal was logic validity. Even if some threads
won't see the changes, they will build their own strings, and the logic
correctness is preserved.
should be volatile to ensure this). But it gives the other threads at
least a chance to reference a new instance variable still without
adding the synchronization overheads.
Why would you intentionally do this wrong, i.e., without
synchronization? "At least a chance"? You're only offering a random
chance that the other threads can see the changes.
Because I believe that my "simple approach" is usually faster than
synchronization, i.e. may be /more optimal/ in some use-cases.
Never share data between threads without synchronization, unless you
really do want to get wrong results in order to speed up your code.
That really seems like a bad tradeoff - programs could be made
arbitrarily fast if we didn't have that pesky need for correct results.
When my approach will give a wrong results?
You are being very, very foolish.
In fact, you direct this words also to the all who believes in benefits
of "atomicity" (e.g. Doug Lea, ...). My approach is just a bit lighter
than used in e.g. AtomicInteger ("get-and-set", and the like...). The
key difference is that my 'source' is not volatile, and I don't care if
I'm always reusing a new value. I decided to do so, because it WASN'T
my primary goal -- just a "nice side-effect". If someones goals are
different, nobody prevents them from being less foolish than me.