1

I was asked recently, the following

Given the following interface, write a class that will leak memory every time Processor#doSomething(String) is called and explain why it does so.

public interface Processor {
    void doSomething(String msg);
}

I am not sure there is memory leak in Java in the same sense as C/C++. What is the significance of an interface here.

Also, I have never seen a # used to call a method.

Can someone explain this to me? Thanks

Raedwald
  • 46,613
  • 43
  • 151
  • 237
rpat
  • 279
  • 2
  • 5
  • 12

1 Answers1

0

A simple implementation would have a static list and when doSomething is called, just keep adding the input String to the list. The reason why is because you're storing a strong reference (via the static member) to the strings so the strings cannot be garbage collected.

Dororo
  • 3,420
  • 2
  • 30
  • 46
  • 1
    When you still hold a strong reference then it is not a memry leak. It is only a leak if you do nit longer have any reference but the object will still not get g/ced. – Polygnome Jun 20 '13 at 21:22
  • That is not the same thing as a memory leak in a C/C++ sense, where your program has no access to the memory you have leaked. Here you do have access to the memory. – rpat Jun 20 '13 at 21:24
  • @polygnome, that's not really correct. Traditional Java usage is that an object that's referenced, but no longer needed, is a leak. – Ernest Friedman-Hill Jun 20 '13 at 21:30
  • @rpat, yes, "leak" does mean something different in Java as compared to C/C++. – Ernest Friedman-Hill Jun 20 '13 at 21:30
  • @Ernest Friedman-Hill: I disagree. As long as you have a strong reference, the memory is not leaked. Your object is still reachable, therefore there is no leak. There is only a leak if your object is unreachable from your code but still not g/ced. There is plenty ways of creating such a real leak even in Java, especially, but not only, when native functions are involved. – Polygnome Jun 20 '13 at 21:35
  • So it is not possible to have a memory leak in the C++ sense? – rpat Jun 20 '13 at 21:38
  • Still, when people say "leak" in Java, they mean simply an unintended retained reference; a common example is an event listener that is never unregistered, preventing GC for a hierarchy of components it references. You can call that whatever you like, but common usage is that it's called a leak. – Ernest Friedman-Hill Jun 20 '13 at 21:57