Exercise Session Week 9 GC and Managed Memory Leaks

Similar documents
Inside the Garbage Collector

Memory management has always involved tradeoffs between numerous optimization possibilities: Schemes to manage problem fall into roughly two camps

Item 18: Implement the Standard Dispose Pattern

Contents. 8-1 Copyright (c) N. Afshartous

Acknowledgements These slides are based on Kathryn McKinley s slides on garbage collection as well as E Christopher Lewis s slides

Course Hours

Memory Usage. Chapter 23

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

DNWSH - Version: 2.3..NET Performance and Debugging Workshop

CS 241 Honors Memory

JAVA PERFORMANCE. PR SW2 S18 Dr. Prähofer DI Leopoldseder

Runtime. The optimized program is ready to run What sorts of facilities are available at runtime

Sustainable Memory Use Allocation & (Implicit) Deallocation (mostly in Java)

CMSC 330: Organization of Programming Languages. Memory Management and Garbage Collection

the gamedesigninitiative at cornell university Lecture 9 Memory Management

Exercise Session Week 8

Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer

Project. there are a couple of 3 person teams. a new drop with new type checking is coming. regroup or see me or forever hold your peace

Memory Management: The Details

Hard Real-Time Garbage Collection in Java Virtual Machines

CMSC 330: Organization of Programming Languages

CS61, Fall 2012 Section 2 Notes

Manual Allocation. CS 1622: Garbage Collection. Example 1. Memory Leaks. Example 3. Example 2 11/26/2012. Jonathan Misurda

Exercise Session Week 8

:.NET Won t Slow You Down

C#: framework overview and in-the-small features

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Agenda. CSE P 501 Compilers. Java Implementation Overview. JVM Architecture. JVM Runtime Data Areas (1) JVM Data Types. CSE P 501 Su04 T-1

Garbage Collection. Hwansoo Han

Java and C# in Depth

Garbage Collection: Automatic Memory Management in the Microsoft.NET Framework

CS842: Automatic Memory Management and Garbage Collection. Mark and sweep

Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

A new Mono GC. Paolo Molaro October 25, 2006

CMSC 330: Organization of Programming Languages

CS577 Modern Language Processors. Spring 2018 Lecture Garbage Collection

Managed runtimes & garbage collection. CSE 6341 Some slides by Kathryn McKinley

Exercise Session Week 6

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Name, Scope, and Binding. Outline [1]

Memory and C++ Pointers

Managed runtimes & garbage collection

CS 345. Garbage Collection. Vitaly Shmatikov. slide 1

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 9.

Exercise Session Week 7

A deep dive into QML memory management internals

Compiler Construction

Java: introduction to object-oriented features

Compiler Construction

Implementation Garbage Collection

Run-time Environments - 3

COMP 524 Spring 2018 Midterm Thursday, March 1

What goes inside when you declare a variable?

Reference Counting. Reference counting: a way to know whether a record has other users

CPSC 213. Introduction to Computer Systems. Instance Variables and Dynamic Allocation. Unit 1c

Reference Counting. Reference counting: a way to know whether a record has other users

Garbage Collection. Akim D le, Etienne Renault, Roland Levillain. May 15, CCMP2 Garbage Collection May 15, / 35

Habanero Extreme Scale Software Research Project

Myths and Realities: The Performance Impact of Garbage Collection

Garbage Collection. Steven R. Bagley

Q1: /8 Q2: /30 Q3: /30 Q4: /32. Total: /100

Estimating the Impact of Heap Liveness Information on Space Consumption in Java

Memory. don t forget to take out the

Harmony GC Source Code

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

G Programming Languages - Fall 2012

CA341 - Comparative Programming Languages

CSE 100: C++ TEMPLATES AND ITERATORS

MEMORY MANAGEMENT HEAP, STACK AND GARBAGE COLLECTION

Garbage Collection. Vyacheslav Egorov

Garbage Collection Algorithms. Ganesh Bikshandi

Dynamic Memory Allocation

Java: exceptions and genericity

NUMA in High-Level Languages. Patrick Siegler Non-Uniform Memory Architectures Hasso-Plattner-Institut

CSCI-1200 Data Structures Fall 2011 Lecture 24 Garbage Collection & Smart Pointers

the gamedesigninitiative at cornell university Lecture 10 Memory Management

Glacier: A Garbage Collection Simulation System

CS558 Programming Languages

Run-Time Environments/Garbage Collection

Concurrency: a crash course

Garbage Collection. CS 351: Systems Programming Michael Saelee

Names, Scope, and Bindings

Programming Language Implementation

Precise Garbage Collection for C. Jon Rafkind * Adam Wick + John Regehr * Matthew Flatt *

Robust Memory Management Schemes

CPSC 213. Introduction to Computer Systems. Winter Session 2017, Term 2. Unit 1c Jan 24, 26, 29, 31, and Feb 2

StackVsHeap SPL/2010 SPL/20

Microsoft Visual C# Step by Step. John Sharp

Names, Scope, and Bindings

6.172 Performance Engineering of Software Systems Spring Lecture 9. P after. Figure 1: A diagram of the stack (Image by MIT OpenCourseWare.

Java Memory Management. Märt Bakhoff Java Fundamentals

The Z Garbage Collector Low Latency GC for OpenJDK

C11: Garbage Collection and Constructors

CSCI-1200 Data Structures Spring 2017 Lecture 27 Garbage Collection & Smart Pointers

Motivation for Dynamic Memory. Dynamic Memory Allocation. Stack Organization. Stack Discussion. Questions answered in this lecture:

A Trace-based Java JIT Compiler Retrofitted from a Method-based Compiler

Advanced Programming & C++ Language

Memory Leak. C++: Memory Problems. Memory Leak. Memory Leak. Pointer Ownership. Memory Leak

CS558 Programming Languages

Transcription:

Chair of Software Engineering Java and C# in Depth Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exercise Session Week 9 GC and Managed Memory Leaks

Overview Managed memory Why GC? GC overview Tricks & Memory Leaks Performance considerations 2

Pre-GC era void Foo(int k){ double* a = new double[k]; delete a;// memory leak! Plus, Undefined behavior (UB) void Foo3(int k){ int* bar = new int[k]; delete[] bar;.. delete[] bar; //UB Bar* Create(){return new Bar; void Foo2(){ Bar* g = Create(); //forgot to delete, memory leak! void Foo4(){ Bar* g = new Bar; free(g); //UB, memory leak! void Foo5(){ Bar* g = new Bar; delete g; g.crunch();//ub! 3

Pre-GC era 2 Reference counting to the rescue! Bar* Create(){.. void BetterFoo(){ std::shared_ptr<bar> ref(create());//1 ref { std::shared_ptr<bar> ref2(ref)// 2 refs // 1 ref.. //0 refs, Bar deleted Is this enough? 4

Cyclic references void FooNode(){ Node *a = new Node; Node *b = new Node; a->next = new std::shared_ptr(b); b->next = new std::shared_ptr(a);.. Even if there is no references outside to a, or b, they still cannot be deleted! Need another approach! 5

GC essentials: Mark & Compact Stage 0: Stop all running threads Stage 1: Mark reachable objects from the roots What are roots? All local (stack) variables in all threads Static variables Content of CPU registers etc Mark Stage 2: Compact everything that is marked. Everything else is garbage (no way to reach it) Compact 6

GC: finalization File f = new File( ); //consumes the machine resources Garbage collection is nondeterministic! How does a framework know that it needs to close a file? Need to finalize some objects C# : ~File(){.. Java: protected void finalize(){ 7

GC: Mark & Compact Revised(C#) Stage 0: Stop all running threads Stage 1: Mark reachable objects from the roots. Put the finalizable objects to Freachable (finalizerreachable queue), also mark them Stage 2: Compact everything that is marked. Everything else is garbage (no way to reach it) Finalizer thread: Maintains the finalization queue, runs object finalizers in own thread. May run in parallel to actual program execution Consequences: Finalizable objects take longer to be collected => do not use without necessity 8

GC: generations Optimization technique: do not process the entire heap, until necessary 9

GC: Non-determinism SqlConnection conn = new SqlConnection( ); ~SqlConnection { //cleanup unmanaged resources, close the physical connection When will connection be closed? Is it guaranteed to close at all? GC is when the operating environment automatically reclaims memory that is no longer being used by the program. It does this by tracing memory starting from roots to identify which objects are accessible The job of a firefighter is "driving a red truck and spraying water." Insights: If the amount of RAM available to the runtime is greater than the amount of memory required by a program, then a memory manager which employs the null garbage collector is a valid memory manager. A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination. 10

GC: Disposable pattern(c#) interface IDisposable{ void Dispose(); - Deterministic finalization For unmanaged resource holders Disposable pattern: class Holder : IDisposable{ //some unmanaged resource ~Holder(){ Dispose(false); protected virtual void Dispose(bool disposing){// if class is sealed, this method is private if(disposing){ //managed cleanup //free unmanaged resources: close file handlers, db connections, free unmanaged memory public void Dispose(){ Dispose(true); GC.SupressFinalize(this); 11

GC: managed memory leak -1 class Processor { MailManager _bar; public Processor(MailManager bar) { _bar = bar; _bar.newmail += OnNewMail; void OnNewMail(object sender, EventArgs e) { public void DoSmth(){.. var bar = new MailManager(); while(!bar.stopped) { var f = new Processor(bar); f.dosmth(); Memory leak because of the event subscription. class MailManager { public event EventHandler NewMail; //other methods Ways to solve: Unsubscribe, when object is not needed WPF WeakEventManager Custom Weak Events implementation 12

GC: managed memory leak - 2 A snippet from server application: while(!isstopped) { var data = (Foo)HttpContext.Current.Session[ userdata"] LocalDataStoreSlot mydata; mydata=thread.getnameddataslot( userdata ); Thread.SetData(myData, data); //continue to listen while(!isstopped){ var data = new Foo (); dict.add ( userdata, data); Thread Local Storage: continues to keep data, until it is explicitly cleared. Can be thought as static dictionary. Again, the problem is that objects live longer, than needed GC is unable to help with that! How to solve? Thread.SetData(myData, null), when finished with processing 13

GC: enough memory?(c#) Large Object Heap (LOH) stores the objects: sizeof(object) >= 85 kb double[], with size >= 1000 85k threshold, when compacting does not provide any performance improvements Memory in LOH does not get compacted => May end with OutOfMemoryException, even if there is enough memory in LOH s fragments Insight: Use large objects with care 14

GC: out of scope Object resurrection Unmanaged memory leaks Critical Finalization Weak References Interaction with unmanaged memory(memory pins) GC modes (server vs client) Debugging memory leaks(windbg, perfmon) 15

References GC explained : http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx J. Richter weak events: http://wintellect.com/blogs/jeffreyr/weak-event-handlers Disposable pattern: http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx Large Object Heap: http://msdn.microsoft.com/en-us/magazine/cc534993.aspx 16