Wednesday 12 July 2017

Java: What will happen when an infinite loop is called to create the objects in the same Reference?



package com.java.gc;
import java.util.List;
import java.util.ArrayList;

class Finalize extends Thread {
     int[] array;
     private int thread;
     public Finalize(int thread) {
           array = new int [1000000];
           this.thread = thread;
     }

     @Override
     public void run() {
           for (int i = 0; i < array.length; i++) {
                array[i] = i;
           }
     }
    
     @Override
     protected void finalize() throws Throwable {
           System.err.println("finalize " + thread);
     }
}

public class TestFinalize {
     public static void main(String[] args) {
           int counter = 0;
          
           List<Finalize> list = new ArrayList<Finalize>();
          
           while(true) {
                Finalize finalize = new Finalize(counter++);
               
                /** Uncomment the below line will lead to
                 * "java.lang.OutOfMemoryError: Java heap space"
                 *
                 *  However, when the line is commented then all
                 *  finalize object are eligible for garbage collection and finalize
                 *  method will be called for each object while garbage collection.
                 */
                //list.add(finalize);
                finalize.start();
           }
     }
}

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is commented.
finalize 0
finalize 19
finalize 20
finalize 21
finalize 14
finalize 15
finalize 16
finalize 17
finalize 18
finalize 9

Output:
When objects are eligible for garbage collection i.e when list.add(finalize) is uncommented.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
     at com.java.gc.Finalize.<init>(TestFinalize.java:10)

     at com.java.gc.TestFinalize.main(TestFinalize.java:33)

Tuesday 11 July 2017

Java: How do you access a parent class method two levels down?

We don't: it violates encapsulation.

It is fine to say, "No, I don't want my own behavior - I want my parent's behavior" because it's assumed that you'll only do so when it maintains your own state correctly.

However, you can't bypass your parent's behavior - that would stop it from enforcing its own consistency. If the parent class wants to allow you to call the grandparent method directly, it can expose that via a separate method... but that's up to the parent class.

Workaround using flag:
package com.java.oops;
/**
 * Grand Parent Class
 */
class AClass {
     public void method(boolean gpFlag) {
           System.out.println("Class A");
     }
}

/**
 * Parent Class.
 */
class BClass extends AClass {
     public void method(boolean gpFlag) {
           super.method(gpFlag);
           if(gpFlag) {
                return;
           }
           System.out.println("Class B");
     }
}

/**
 * Child Class.
 */
class CClass extends BClass {
     public void method(boolean gpFlag) {
           super.method(gpFlag);
           System.out.println("Class C");
     }
}

public class CallGrandParent {
     public static void main(String[] args) {
           CClass c = new CClass();
           boolean gpFlag = true;
           c.method(gpFlag);
     }
}
Output:
Class A
Class C



Thursday 29 June 2017

Ping an IP address in Java | Java Networking

We can ping an IP address using java.net.InetAddress.isReachable() method.

This example is by using ProcessBuilder class, Process class. ProcessBuilder class is used to create operating system processes and ProcessBuilder.start() starts the sub-process which will execute the ping command.
package com.java.networking;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class PingIP {
    
     static voidrunOSCommands(ArrayList<String> commandList) throws Exception {
           /** creating the sub process, execute system command. */
           ProcessBuilder build = newProcessBuilder(commandList);
          
           Process process = build.start();

           /** to read the output. */
           BufferedReader input = newBufferedReader(new InputStreamReader(process.getInputStream()));
           BufferedReader error = newBufferedReader(new InputStreamReader(process.getErrorStream()));
          
           String s = null;
           System.out.println("Ping result: ");
          
           while((s = input.readLine()) != null) {
                System.out.println(s);
           }
          
           System.out.println("Print error (if any): ");
           while((s = error.readLine()) != null) {
                System.out.println(s);
           }
     }

     public static void main(String args[]) throws Exception {
          
           /** Initialize the command list. */
           ArrayList<String> commandList = newArrayList<String>();

           commandList.add("ping");
           commandList.add("www.google.com");
          
           runOSCommands(commandList);
     }
}
Ping result:
Pinging www.google.com [74.125.68.104] with 32 bytes of data:
Reply from 74.125.68.104: bytes=32 time=403ms TTL=45
Reply from 74.125.68.104: bytes=32 time=341ms TTL=45
Reply from 74.125.68.104: bytes=32 time=359ms TTL=45
Reply from 74.125.68.104: bytes=32 time=329ms TTL=45

Ping statistics for 74.125.68.104:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 329ms, Maximum = 403ms, Average = 358ms
Related Posts Plugin for WordPress, Blogger...