Why finalize() method has empty body? - object

This is how the finalize() is defined in Object class:
protected void finalize() throws Throwable { }
Can anyone tell me where is the code inside the method? I mean how Garbage Collector calls a method with empty body to perform cleanup activities associated with the object?

Related

Mock Void type in Mockito

Say Foo is the class we mock and Foo has a method named Foo.bar() which returns type Void (not void). How can we use Mockito to mock this method?
Not sure whether returning null in this case would be the best solution.
Because Void is final and not instantiable, there is no instance you could ever return. In production, that method can only return null (if it returns at all), and that should hold true in your tests as well.
Note that Mockito will return null by default for methods that return Object instances other than collections and primitive wrappers, so you should only need to stub a method that returns Void if you need to override a spied method:
// Spy would have thrown exception
// or changed object state
doReturn(null).when(yourSpy).someMethodThatReturnsVoid();
Or throw an exception:
// Throw instead of returning null by default
when(yourMock.someMethodThatReturnsVoid()).thenThrow(new RuntimeException());
Or react with an Answer:
when(yourMock.someMethodThatReturnsVoid()).thenAnswer(new Answer<Void>() {
#Override public void answer(InvocationOnMock invocation) {
// perform some action here
return null;
}
}

What happens if I instantiate an object within its own constructor?

//object class
public class test
{
public test()
{
test t1 = new test();
}
}
//client class in same folder
public class Client
{
public static void main(String[] args)
{
test t = new test();
}
}
Does this just make infinite empty test objects?
What happens to the computer memory space/RAM do things just get deleted as more objects are continuously created?
Your initial reasoning is correct: you get an "infinite" number of test objects. Each object creates a new one. The constructor for the first object created (by main) never finishes.
However, the Java Virtual Machine (JVM) has a limit on the stack size. Every time the constructor calls the next constructor, an entry is pushed onto the stack. Within a short amount of time, you'll get a stack overflow exception and your program will be terminated.

How to access objects declared and initialized outside the call() method of JavaRDD

I am unable to access objects declared and initialized outside the call() method of JavaRDD.
In the below code snippet, call() method makes a fetch call to C* but since javaSparkContext is defined outside the call method scope so compiler give a compilation error.
stringRdd.foreach(new VoidFunction<String>() {
#Override
public void call(String str) throws Exception {
JavaRDD<String> vals = javaFunctions(javaSparkContext).cassandraTable("schema", "table", String.class)
.select("val");
}
});
In other languages I have used closure to do this but not able to achieve the same here.
Can someone suggest how to achieve this in the current code context.

Confusion with IDisposable

I have some nagging doubts about the correct way to implement IDisposable. Consider the following scenario...
public class Foo : IDisposable {...}
public class Bar : IDisposable {
private bool disposed = false;
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public Bar(Foo foo) {
this.MyFoo = foo;
}
~Bar() {
Dispose(false);
}
protected virtual void Dispose(bool disposing) {
if (!this.disposed) {
if (disposing) {
if (MyFoo != null) {
this.MyFoo.Dispose();
this.MyFoo = null;
}
}
this.disposed = true;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
}
My questions are:
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
The above pattern seems to crop up quite a lot (particularly with DI), but I don't seem to be able to find a concrete example of the correct way to structure this.
Refer to Excellent MSDN article
Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
1) If a class creates a disposable object, should it call the Dispose() method on that object in its own Dispose() method?
Yes it should. Otherwise also, Dispose will be called. But that will increase life of object by atleast 1 generation. This is due to the finalizer in the class definition. Refer to the article link above.
2) If a disposable object is passed to a class as a reference, should that class still call the Dispose() method on that reference object, or should it leave it to the class that created the object in the first place?
It is responsibility of caller (more specifically the class which has created an instance) to call the Dispose method.
~Bar() {
Dispose(false);
}
Whenever you find yourself writing code like this, take a deep breath first and ask "do I actually need a finalizer?" It is extremely rare that you need one, a finalizer is only required when you take ownership of an unmanaged resource yourself.
The first litmus test is "does the finalizer actually do anything?" That's clear if you follow the code. It calls Dispose(false) and that code only does something when the argument is true. What follows is that you don't need a finalizer. This is entirely normal, finalizers is something that Microsoft worries about. They wrote the .NET framework classes that wrap an unmanaged resource. FileStream, Socket, etcetera. And above all, the SafeHandle classes, designed to wrap operating system handles. They have their own finalizer, you don't rewrite one yourself.
So without a finalizer, the code entirely collapses to the simple and correct implementation, you only need to call the Dispose() method of any disposable objects you store yourself:
public class Bar : IDisposable {
private readonly Foo MyFoo;
public Bar() {
this.MyFoo = new Foo();
}
public void Dispose() {
MyFoo.Dispose();
}
}

IDisposable + finalizer pattern

Looking at the IDisposable pattern + Finalizer pattern, there is something I don't understand:
public class ComplexCleanupBase : IDisposable
{
private bool disposed = false; // to detect redundant calls
public ComplexCleanupBase()
{
// allocate resources
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// dispose-only, i.e. non-finalizable logic
}
// shared cleanup logic
disposed = true;
}
}
~ComplexCleanupBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
From my understanding the pattern should be implemented like above.
1) Calling Dispose() fires GC.SuppressFinalize(this), which means that the object should not be put on the finalizer queue as its already properly disposed? That helps to free up the object faster?
2) But what if I am not calling Dispose() on this object at all? In that case the finalizer should kick in, correct? But Dispose(false); does absolutely nothing (only setting disposed = true). Is this intended? It feels like as if something is missing...
Question 1: Yes, if GC.SuppressFinalize is not called the object will be placed on the finalizer queue AND will move up a generation (if not already gen 2), which means that the memory for that object will not be reclaimed until the next pass of GC for the new generation.
Question 2: Your comment //shared cleanup logic is where the shared cleanup logic will go, this is where things other than setting disposed = true would happen.
Also, an aside: if your dispose logic should only be called once, consider acquiring a lock, an uncontested lock is very fast in .Net:
public class ComplexCleanupBase : IDisposable
{
private volatile bool disposed = false; // to detect redundant calls
private readonly object _mutex = new object();
protected virtual void Dispose(bool disposing)
{
if (!Monitor.TryEnter(_mutex))
{
// We're already being disposed.
return;
}
try
{
if (!disposed)
{
if (disposing)
{
// dispose-only, i.e. non-finalizable logic
}
// shared cleanup logic
disposed = true;
}
}
finally
{
Monitor.Exit(_mutex);
}
}
... other methods unchanged
}
If Dispose(false) isn't going to do anything, that's a very good indication that neither your class nor any class derived from it should include a C#-style "destructor" nor override Finalize, and the "disposing" argument should be regarded as a dummy whose purpose is to give the protected Dispose method a different signature from the public one.
Note that implementing a destructor or overriding Finalize in a derived class, when the parent class is not expecting such behavior, can produce Heisenbugs. Among other things, the GC can sometimes decide that a class object has been abandoned, triggering its finalizer/destructor, even while an entity referred to by a field of the class is being used. For example, suppose a static class usbThingie manipulates USB controllers using integer handles, and a wrapper class usbWrapper does something like:
UInt32 myHandle;
void sendData(Byte data[])
{
UsbThingie.send(myHandle, data[0], data.Length);
}
If a sendData() call is the last thing done to an instance of usbWrapper before it is abandoned, it would be possible for the garbage-collector to observe that once UsbThingie.send() is called--even before it returns--no further references will exist to the usbWrapper, and thus it can safely trigger the finalizer. If the finalizer tries to close the channel referred to by myHandle, that might disrupt the transmission that was taking place; if usbThingie isn't thread-safe, there's no telling what might happen.

Resources