JMX and MBeans

JMX is used to manage Java processes and to control Java components on a server. MBeans are POJO (Plain Old Java Objects) that have attributes and operations. These MBeans are registered with a JMX Container and are managed through a special web page called a JMX Console. These MBeans, its operations and attributes show up on the JMX console. Through the JMX console (web page) certain operations can be performed on the MBean class, and its attribute values changed. Any Java class can be managed as MBeans registered in a JMX container. MBeans are used for user interaction, more like super-user interaction. The super user (like an administrator) can click on the MBean on the JMX console to perform some operation or change MBean attributes.
So what you do is write a Java class with some methods; then you register that MBean with the JMX container so that it shows up on the JMX console.
Log4j has jmx capability. If log4j is registered in a JMX server then it shows up as an MBean. You can click on it thru the console and change its logging level without having to restart the server. You may want to change error logging from ERROR to DEBUG by clicking on the log4j MBean in the JMX console. After you are done with debugging you could click on it to switch back to ERROR.

HelloMBean.java

/* HelloMBean.java – MBean interface describing the management
operations and attributes for the Hello World MBean. In this case
there is an operation, “concatt”, attribute, “Name”. */


package com.example.mbeans;

public interface HelloMBean {
	// operation

	public String concatt(String x, String y);

	// attribute

	public String getName();

	public void setName(String name);

}

Hello.java

/* Hello.java – MBean implementation for the Hello World MBean. This class must implement all the Java methods declared in the HelloMBean interface, with the appropriate behavior for each one. */


package com.example.mbeans;

import java.lang.*;

public class Hello implements HelloMBean {
	private String name = "Reginald";

	public String concatt(String x, String y) {
		return x + y;
	}

	/*
	 * Getter for the Name attribute. The pattern shown here is frequent: the
	 * getter returns a private field representing the attribute value. Consider
	 * an attribute representing statistics such as uptime or memory usage, for
	 * example. Being read-only just means that it can't be changed through the
	 * management interface.
	 */
	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

jmx.jsp

<%@ page import="javax.management.*,java.util.*,java.lang.management.*,com.example.mbeans.*"%>
<%
// Get the Platform MBean mbs mbeansever
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
// Construct the ObjectName for the MBean we will register
ObjectName name = new ObjectName("com.example.mbeans:type=Hello");
Hello mbean = null;
//Update MBean with request parameter
String newvalue = (String)request.getParameter("Name");
if (newvalue == null || newvalue.length() <= 0)
{
// Create the Hello World MBean
mbean = new Hello();
// Register the Hello World MBean
mbs.registerMBean(mbean, name);
}
try {
if (newvalue != null && newvalue.length() > 0) {
Attribute attr = new Attribute("Name", newvalue);
mbs.setAttribute(name, attr );
}
//Get latest mbean attribute
String value = (String)mbs.getAttribute( name,"Name");
out.println("THE attribute of the mbean has changed to "+value);
 
%>
 
 
MBean <%= name.getCanonicalName() %>
 
 
<FORM METHOD="post" ACTION="jmx.jsp">
    <TABLE ALIGN="left" BORDER="1" WIDTH="40%" CELLPADDING="3">
        <TR>
            <TH WIDTH="23%">Attribute</TH>
            <TH WIDTH="35%">Value</TH>
        </TR>
        <TR>
            <TD><B>Enter Name: </B>
            </TD>
            <TD><INPUT TYPE="text" NAME="Name" VALUE="<%= value %>"
                SIZE="34%">
            </TD>
        </TR>
        <TR>
            <TD ALIGN=LEFT><INPUT TYPE="submit" VALUE="UPDATE">
            </TD>
        </TR>
    </TABLE>
</FORM>
 
<%
} catch (Exception e) {
out.println(e.getMessage());
}
 
%>

jmx_call.jsp

<%@ page import="javax.management.*,java.util.*,java.lang.management.*,com.example.mbeans.*"%>
 
<%
    // Get the Platform MBean mbs mbeansever
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    // Construct the ObjectName for the MBean we will register
    ObjectName name = new ObjectName("com.example.mbeans:type=Hello");
    Hello mbean = null;
    //Update MBean with request parameter
    String newvalue1 = (String) request.getParameter("valueA");
    String newvalue2 = (String) request.getParameter("valueB");
    String value = null;
 
    if (newvalue1 == null && newvalue2 == null) {
        // Create the Hello World MBean
        mbean = new Hello();
        // Register the Hello World MBean
        mbs.registerMBean(mbean, name);
    }
    try {
        if ((newvalue1 != null && newvalue1.length() > 0
                && newvalue2 != null && newvalue2.length() > 0)) {
            Object params[] = { newvalue1, newvalue2 };
            String[] signature = { "java.lang.String",
                    "java.lang.String" };
            value = (String) mbs.invoke(name, "concatt", params,
                    signature);
            out.print("THE String is " + value);
        }
 
        //Get latest mbean attribute
%>
MBean
<%=name.getCanonicalName()%>
<FORM METHOD="post" ACTION="jmx_call.jsp">
    <TABLE ALIGN="left" WIDTH="40%" CELLPADDING="3">
        <TR>
            <TH WIDTH="23%">Add</TH>
            <TH WIDTH="35%">These values</TH>
        </TR>
        <TR>
            <TD><B>Enter Values: </B></TD>
            <TD><INPUT TYPE="text" NAME="valueA" VALUE=0 SIZE="34%">
            </TD>
            <TD><INPUT TYPE="text" NAME="valueB" VALUE=0 SIZE="34%">
            </TD>
        </TR>
        <TR>
            <TD ALIGN=LEFT><INPUT TYPE="submit" VALUE="UPDATE"></TD>
        </TR>
    </TABLE>
</FORM>
 
<%
    } catch (Exception e) {
        out.println(e.getMessage());
    }
%>

Interview Blockers


Q:If class A has a method
public void foo throws Exception E, Exception F
and
class B extends A has the method
public void foo throws Exception E, Exception F, Exception G
Will the code compile?
A: No, an overriden method cannot throw more exceptions than the method in the parent class.

Q:If class A has a method
private void foo
and
class B extends A
has a method
public void foo
will the code compile?
A: Yes an overridden method can be made more accessible than the method in the parent class

Q:What is the difference between an include file directive and a jsp:include action?
A:The file included using the directive is included before the jsp is compiled while the file included using the action is included after the jsp is compiled. In other words include directive includes static content at compile time and action include includes static or dynamic content at run time.

Q:How will you avoid caching in JSP?
A:
response.setHeader(“Pragma”,”no-cache”);
response.setHeader(“Cache-Control”,”no-store”);

Q:What is the return type of ejbFindByPrimaryKey() in the entity bean class and the return type of findByPrimaryKey() in the Home interface of the entity bean
A: The bean class method will return a primarykey type while the home interface method will return a bean type

Q:How will you implement a custom taglib?
A: The class should extend TagSupport and implement doStartTag() or doEndTag() methods. Then write an xml file with tld extension to describe this class and declare the tld file in web.xml.

Q: How does java implement session tracking? What is the default mechanism used by java for session tracking?
A: Java implements Session tracking using cookies or url rewriting. The default mechanism is use of cookies. When cookies are disabled url rewriting is used.

Q: What is a DynaForm?
A: A struts form bean can be defined in struts-config.xml without explicitly writing a Java class for the form bean. This is called a DynaForm.

Q: Name any three top level interfaces in the Collection API?
A: SET, SORTED SET, LIST, MAP, SORTED MAP, ITERATOR, LIST ITERATOR

What are the types of classloaders?
http://javapapers.com/core-java/java-class-loader/

Bootstrap Class Loader – loads classes that are part of JRE. It’s a native implementation.

Extensions Class Loader – load classes that are part of JRE extensions in lib\ext folder.

Systems Class Loader – loads classes that are on the Java classpath.

Difference between ClassNotFoundException and NoClassDefFoundError
ClassNotFoundException and NoClassDefFoundError occur when a particular class is not found at runtime. However, they occur at different scenarios.ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath. NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.NoClassDefFoundError is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.

So if you have code like this…
public class Foo {
   public class methodA() {
       //lines of code
       pkg.Bar b = new pkg.Bar();
       }
}
Now, let’s say you don’t have pkg.Bar class available during compile, you will obviously get a compile time error.
If you have the pkg.Bar class available during compile, that’s good.
However, if you don’t have it at runtime (e.g. you missed bundling it into the war file), then you will get a NoClassDefFoundError when you run the application.
Ok, now if you are using java reflection like this:
public class Foo{
   public class methodA() {
      //lines of code
      Class.forName("pkg.Bar");
      }
}
Now, let’s say you don’t have pkg.Bar class available during compile time, you will not get a compile time error.  This is because you don’t have a hard reference. You are simply passing a string into that method.
If you don’t have it at runtime (e.g. you missed bundling it into the war file), then you will get a ClassNotFoundException when you run the application.

NoClassDefFoundError – available at compile time, missing at runtime, available at compile time; not loaded by class loader at runtime using Class.forName -> ClassNotFoundException.

What are the advantages of using enum?

Enums in Java 5+ are basically classes that have a predefined set of instances. They are intended as a replacement for, say, a collection of integer constants. They are preferably to constants as they can enforce type safety. The advantages are:
1. Type safety. You can declare a function argument, return type, class member or local variable to be a particular Enum type and the compiler will enforce type safety; Enums are basically classes.
2. They can implement interfaces, have behavior and so on.

http://www.journaldev.com/1933/java-servlet-filter-example-tutorial

Why do we need Servlet Filter?
We can manage session in web application and if we want to make sure that a resource is accessible only when user session is valid, we can achieve this using servlet session attributes. The approach is simple but if we have a lot of servlets and jsps, then it will become hard to maintain because of redundant code. If we want to change the attribute name in future, we will have to change all the places where we have session authentication.
That’s why we have servlet filter. Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.
Some common tasks that we can do with servlet filters are:
a. Logging request parameters to log files.
b. Authentication and autherization of request for resources.
c. Formatting of request body or header before sending it to servlet.
d. Compressing the response data sent to the client.
e. Alter response by adding some cookies, header information etc.
f. Servlet filters are pluggable and configured in deployment descriptor (web.xml) file. g. Servlets and filters both are unaware of each other and we can add or remove a servlet filter just by editing web.xml.
h. We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml

https://www.sitepoint.com/how-to-implement-javas-hashcode-correctly/
How do you implement java hash code correctly?
Computing hash codes is something like compressing equality to an integer value: Equal objects must have the same hash code and for performance reasons it is best if as few non-equal objects as possible share the same hash. This means that hashCode must always be overridden if equals is. Only one thing we should care about: Equal objects should have the same hash code.
When implementing hashCode:

1. Use a the same fields that are used in equals (or a subset thereof).
2. Better not include mutable fields.
3. Consider not calling hashCode on collections.
4. Use a common algorithm unless patterns in input data counteract them.
5. Remember that hashCode is about performance, so don’t waste too much energy unless profiling indicates necessity.

This is how hashCode works: Instances with the same hash code are not necessarily equal but equal instances have the same hash code. HashMap is a collection class that uses this technique. When an element is added, its hash code is used to compute the index in an internal array (called a bucket). If other, non-equal elements have the same hash code, they end up in the same bucket and must be bundled together, e.g. by adding them to a list. When an instance is given to contains, its hash code is used to compute the bucket. Only elements therein are compared to the instance. This way, very few, ideally no equals comparisons are required to implement contains.

How is hashing implemented in Hashtables?

A Hashtable internally contains buckets in which it stores the key/value pairs. When you pass a key/value to the Hashtable , it queries the key’s hashcode. The Hashtable uses that code to determine the bucket in which to place the key/value. By using the hashcode this way, the Hashtable can also quickly determine in which bucket it has placed the value when you try to retrieve it. In Java, the Hashtable responds to a collision by placing multiple values into the same bucket. Creating your own unique hashcodes for your class is not enough, they have to well distributed to avoid hash collisions.

What is hash collision?

In an HashMap the key is an object, that contains hashCode() and equals(Object) methods. When you insert a new entry on the Map, it checks whether the hashCode is already known. Then, it will iterate through all objects with this hashcode, and test their equality with .equals(). If an equal object is found, the new value replace the old one. If not, it will create a new entry in the map. Usually, talking about maps, you use collision when two objects have the same hashCode but they are different. They are internally stored in a list.

How does Java avoid Hash Collisions?

Hash tables deal with collisions in one of two ways.
Option 1: By having each bucket contain a linked list of elements that are hashed to that bucket. This is why a bad hash function can make lookups in hash tables very slow.
Option 2: If the hash table entries are all full then the hash table can increase the number of buckets that it has and then redistribute all the elements in the table. The hash function returns an integer and the hash table has to take the result of the hash function and mod it against the size of the table that way it can be sure it will get to bucket. So by increasing the size, it will rehash and run the modulo calculations which if you are lucky might send the objects to different buckets.
Java uses both option 1 and 2 in its hash table implementations.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is a significant difference between them on how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. The only difference between Hashtable and Synchronized Map is that latter is not a legacy and you can wrap any Map to create it’s synchronized version by using Collections.synchronizedMap() method. ConcurrentHashMap is specially designed for concurrent use i.e. more than one thread. Unlike Hashtable and Synchronized Map, it never locks whole Map, instead, it divides the map into segments and locking is done on those. Though it performs better if a number of reader threads are greater than the number of writer threads.

Null values in Hashtable

As specified in JDK documentation, Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. When HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case. To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and the equals method. Since null isn’t an object, you can’t call .equals() or .hashCode() on it, so the Hashtable can’t compute a hash to use it as a key.

Internal Representation of an Array

Internally an ArrayList uses an Object[]. As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.