Extreme memory usage when `synchronized( this )` is used
Daniel Kozák via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon May 11 02:20:29 PDT 2015
On Mon, 11 May 2015 09:09:07 +0000
tcak via Digitalmars-d-learn <digitalmars-d-learn at puremagic.com> wrote:
> [code]
> import std.stdio;
>
> class Connection{
> private void other() shared{}
>
> public void close() shared{
> synchronized( this ){
> other();
> }
> }
>
> public void hasData() shared{ writeln("Has Data"); }
> }
>
> void main() {
> for(long i=0; i < 250_000_000; ++i){
> auto conn = new shared Connection();
>
> conn.hasData();
>
> conn.close();
> }
> }
> [/code]
>
> With this code, memory usage of program is increasing very fast.
> In about 10 seconds, it reached 100MB for me.
>
> If I comment out `synchronized( this )` line with its
> parentheses, OR remove `(this)` from it, it suddenly turns
> normal. Very little memory usage.
>
> What's happening? Is object instance being stored somewhere at
> each iteration?
>
> --
>
> I tried the same thing by creating synchronisation object instead
> of object itself as blow, still usage lots of memory.
>
> [code]
> import std.stdio;
>
> class Connection{
> private Object syncObject;
>
> public this() shared{
> syncObject = new shared Object();
> }
>
> private void other() shared{}
>
> public void close() shared{
> synchronized( syncObject ){
> other();
> }
> }
>
> public void hasData() shared{ writeln("Has Data"); }
> }
>
> void main() {
> for(long i=0; i < 250_000_000; ++i){
> auto conn = new shared Connection();
>
> conn.hasData();
>
> conn.close();
> }
> }
> [/code]
I think synchronize(this) prevents GC from collect memory
More information about the Digitalmars-d-learn
mailing list