Extreme memory usage when `synchronized( this )` is used

tcak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 11 02:12:13 PDT 2015


On Monday, 11 May 2015 at 09:09:09 UTC, tcak 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 use DMD 2.067.1 on Ubuntu 14.04 64 bit


More information about the Digitalmars-d-learn mailing list