String Word Reverse without Reverse Function

11 08 2014

we have the string = Java programming is fun and we want to reverse that string in each word wise

avaJ gnimmargorp si nuf ,without using any reverse function.

/**
* @author TechSivam
* Reverse the string each word and not to use any string reverse methods.
*/
public class StringReverse {
public static void main(String[] args) {
StringBuffer a = new StringBuffer(“Java programming is fun”);
System.out.println(a);

String[] s=a.toString().split(” “);

for (String string : s) {

for (int i = string.length()-1; i >=0; i–) {
System.out.print(string.charAt(i));
}
System.out.print(” “);
}

}

}

 

 

OUTPUT:

Java programming is fun
avaJgnimmargorp si nuf





Collections in Immutable Class

11 08 2014
  • immutable class in java is not allowing to modify the value of the variables.
  • but in normal immutable class with collections , if we are not using setter method also , we can change the collection values.
  • normally when we use the getter method , we directly return the reference of the collections.
  • here we can change the values for the collection, even though,it is final .

 

public class ImmutableClassCollections {

private final  String name;
private final List arrayList;

public ImmutableClassCollections(String name, List arrayList) {
this.name = name;
this.arrayList = arrayList;
}

public String getName() {
return name;
}

public List getArrayList() {
return arrayList;
}

/**
* @param args
*/
public static void main(String[] args) {
List mylist=new ArrayList<>();
mylist.add(“A”);
mylist.add(“B”);
ImmutableClassCollections example=new ImmutableClassCollections(“Siva”, mylist);

System.out.println(example.getName());

List arrayList2 = example.getArrayList();

for (String string : arrayList2) {
System.out.println(string);
}
System.out.println(“Add C to Array List”);
example.getArrayList().add(“C”);
arrayList2 = (ArrayList) example.getArrayList();
for (String string : arrayList2) {
System.out.println(string);
}

}

}

OUTPUT:

Siva
A
B
Add C to Array List
A
B
C

 

How to Avoid Collection also in Immutable Class:

we can use two approaches in getter method

  1.  create local copy of the collection and return the copy reference only
  2. using collections API-return Collections.unmodifiableXXX(XXX);

 

1) Create  Local Copy:

  • It will create new copy and return that value. so it will not change the original value

public List<String> getArrayList() {
List arrayList1=new ArrayList<>(arrayList);
return arrayList1;
}

OUTPUT:

Siva
A
B
Add C to Array List
A
B

 

Here we are using Collections.unmodifiableList(arrayList);

now we change the return value, it will throw the exception.

public List<String> getArrayList() {
return Collections.unmodifiableList(arrayList);
}

OUTPUT:

Siva
A
B
Add C to Array List
Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at com.ts.immutable.ImmutableClassCollections.main(ImmutableClassCollections.java:42)

 

unmodifiableList Implementation in Collections Class:

 

/**

* Returns an unmodifiable view of the specified list. This method allows
* modules to provide users with “read-only” access to internal
* lists. Query operations on the returned list “read through” to the
* specified list, and attempts to modify the returned list, whether
* direct or via its iterator, result in an
* <tt>UnsupportedOperationException</tt>.<p>
*
* The returned list will be serializable if the specified list
* is serializable. Similarly, the returned list will implement
* {@link RandomAccess} if the specified list does.
*
* @param list the list for which an unmodifiable view is to be returned.
* @return an unmodifiable view of the specified list.
*/
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<>(list));
}





Calculate Java Object Size with Instrumentation

11 08 2014

java.lang.instrument package Provides services that allow Java programming language agents to instrument programs running on the JVM. The mechanism for instrumentation is modification of the byte-codes of methods.

Package Specification

An agent is deployed as a JAR file. An attribute in the JAR file manifest specifies the agent class which will be loaded to start the agent. For implementations that support a command-line interface, an agent is started by specifying an option on the command-line. Implementations may also support a mechanism to start agents some time after the VM has started. For example, an implementation may provide a mechanism that allows a tool to attach to a running application, and initiate the loading of the tool’s agent into the running application. The details as to how the load is initiated, is implementation dependent.

Command-Line Interface

On implementations with a command-line interface, an agent is started by adding this option to the command-line:

-javaagent:jarpath[=options]

jarpath is the path to the agent JAR file. options is the agent options. This switch may be used multiple times on the same command-line, thus creating multiple agents. More than one agent may use the same jarpath. An agent JAR file must conform to the JAR file specification.

The manifest of the agent JAR file must contain the attribute Premain-Class. The value of this attribute is the name of the agent class. The agent class must implement a public static premain method similar in principle to the mainapplication entry point. After the Java Virtual Machine (JVM) has initialized, each premain method will be called in the order the agents were specified, then the real application main method will be called. Each premain method must return in order for the startup sequence to proceed.

The premain method has one of two possible signatures. The JVM first attempts to invoke the following method on the agent class:

public static void premain(String agentArgs, Instrumentation inst);

If the agent class does not implement this method then the JVM will attempt to invoke:

public static void premain(String agentArgs);

The agent class may also have an agentmain method for use when the agent is started after VM startup. When the agent is started using a command-line option, the agentmain method is not invoked.

The agent class will be loaded by the system class loader (see ClassLoader.getSystemClassLoader). This is the class loader which typically loads the class containing the application main method. The premain methods will be run under the same security and classloader rules as the application main method. There are no modeling restrictions on what the agent premain method may do. Anything application main can do, including creating threads, is legal frompremain.

Each agent is passed its agent options via the agentArgs parameter. The agent options are passed as a single string, any additional parsing should be performed by the agent itself.

If the agent cannot be resolved (for example, because the agent class cannot be loaded, or because the agent class does not have an appropriate premain method), the JVM will abort. If a premain method throws an uncaught exception, the JVM will abort.

Starting Agents After VM Startup

An implementation may provide a mechanism to start agents sometime after the the VM has started. The details as to how this is initiated are implementation specific but typically the application has already started and its main method has already been invoked. In cases where an implementation supports the starting of agents after the VM has started the following applies:

  1. The manifest of the agent JAR must contain the attribute Agent-Class. The value of this attribute is the name of the agent class.
  2. The agent class must implement a public static agentmain method.
  3. The system class loader ( ClassLoader.getSystemClassLoader) must support a mechanism to add an agent JAR file to the system class path.

The agent JAR is appended to the system class path. This is the class loader that typically loads the class containing the application main method. The agent class is loaded and the JVM attempts to invoke the agentmain method. The JVM first attempts to invoke the following method on the agent class:

public static void agentmain(String agentArgs, Instrumentation inst);

If the agent class does not implement this method then the JVM will attempt to invoke:

public static void agentmain(String agentArgs);

The agent class may also have an premain method for use when the agent is started using a command-line option. When the agent is started after VM startup the premain method is not invoked.

The agent is passed its agent options via the agentArgs parameter. The agent options are passed as a single string, any additional parsing should be performed by the agent itself.

The agentmain method should do any necessary initialization required to start the agent. When startup is complete the method should return. If the agent cannot be started (for example, because the agent class cannot be loaded, or because the agent class does not have a conformant agentmain method), the JVM will not abort. If the agentmain method throws an uncaught exception it will be ignored.

Manifest Attributes

The following manifest attributes are defined for an agent JAR file:

Premain-Class
When an agent is specified at JVM launch time this attribute specifies the agent class. That is, the class containing the premain method. When an agent is specified at JVM launch time this attribute is required. If the attribute is not present the JVM will abort. Note: this is a class name, not a file name or path.
Agent-Class
If an implementation supports a mechanism to start agents sometime after the VM has started then this attribute specifies the agent class. That is, the class containing the agentmain method. This attribute is required, if it is not present the agent will not be started. Note: this is a class name, not a file name or path.
Boot-Class-Path
A list of paths to be searched by the bootstrap class loader. Paths represent directories or libraries (commonly referred to as JAR or zip libraries on many platforms). These paths are searched by the bootstrap class loader after the platform specific mechanisms of locating a class have failed. Paths are searched in the order listed. Paths in the list are separated by one or more spaces. A path takes the syntax of the path component of a hierarchical URI. The path is absolute if it begins with a slash character (‘/’), otherwise it is relative. A relative path is resolved against the absolute path of the agent JAR file. Malformed and non-existent paths are ignored. When an agent is started sometime after the VM has started then paths that do not represent a JAR file are ignored. This attribute is optional.
Can-Redefine-Classes
Boolean (true or false, case irrelevant). Is the ability to redefine classes needed by this agent. Values other than true are considered false. This attribute is optional, the default is false.
Can-Retransform-Classes
Boolean (true or false, case irrelevant). Is the ability to retransform classes needed by this agent. Values other than true are considered false. This attribute is optional, the default is false.
Can-Set-Native-Method-Prefix
Boolean (true or false, case irrelevant). Is the ability to set native method prefix needed by this agent. Values other than true are considered false. This attribute is optional, the default is false.

An agent JAR file may have both the Premain-Class and Agent-Class attributes present in the manifest. When the agent is started on the command-line using the -javaagent option then the Premain-Class attribute specifies the name of the agent class and the Agent-Class attribute is ignored. Similarly, if the agent is started sometime after the VM has started, then the Agent-Class attribute specifies the name of the agent class (the value of Premain-Class attribute is ignored).

 

Example:

  • in this instrumentation we can apply on jar.
  • so for that we need to create jar using ant.
  • first we create instrument Agent and in manifest we will configure the Agent.
  • using and create jar
  • after that in command line we need to pass the object details to the agent.
  • java -javaagent:Instrumentation.jar
    -cp Instrumentation.jar techsivam.examples.InstrumentSampleObjects

EmptyClass:

package techsivam.examples;

public class EmptyClass {

int i=0;
String s=”Siva”;
Float f=5.3F;
}

InstrumentationAgent:

package techsivam.examples;

import java.lang.instrument.Instrumentation;
import static java.lang.System.out;
/**
* Simple example of an Instrumentation Agent
*/
public class InstrumentationAgent
{
/** Handle to instance of Instrumentation interface. */
private static volatile Instrumentation globalInstrumentation;

/**
* Implementation of the overloaded premain method that is first invoked by
* the JVM during use of instrumentation.
*
* @param agentArgs Agent options provided as a single String.
* @param inst Handle to instance of Instrumentation provided on command-line.
*/
public static void premain(final String agentArgs, final Instrumentation inst)
{
out.println(“premain…”);
globalInstrumentation = inst;
}

/**
* Implementation of the overloaded agentmain method that is invoked for
* accessing instrumentation of an already running JVM.
*
* @param agentArgs Agent options provided as a single String.
* @param inst Handle to instance of Instrumentation provided on command-line.
*/
public static void agentmain(String agentArgs, Instrumentation inst)
{
out.println(“agentmain…”);
globalInstrumentation = inst;
}

/**
* Provide the memory size of the provided object (but not it’s components).
*
* @param object Object whose memory size is desired.
* @return The size of the provided object, not counting its components
* (described in Instrumentation.getObjectSize(Object)’s Javadoc as “an
* implementation-specific approximation of the amount of storage consumed
* by the specified object”).
* @throws IllegalStateException Thrown if my Instrumentation is null.
*/
public static long getObjectSize(final Object object)
{
if (globalInstrumentation == null)
{
throw new IllegalStateException(“Agent not initialized.”);
}
return globalInstrumentation.getObjectSize(object);
}
}

InstrumentSampleObjects:

package techsivam.examples;

import static java.lang.System.out;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
* Build up some sample objects and throw them at the Instrumentation example.
*
* Might run this class as shown next:
* java -javaagent:dist\agent.jar -cp dist\agent.jar techsivam.examples.InstrumentSampleObjects
*
* @author TechSivam
*/
public class InstrumentSampleObjects
{
public enum Color
{
RED,
WHITE,
YELLOW
}

/**
* Print basic details including size of provided object to standard output.
*
* @param object Object whose value and size are to be printed to standard
* output.
*/
public static void printInstrumentationSize(final Object object)
{
out.println(
“Object of type ‘” + object.getClass() + “‘ has size of “
+ InstrumentationAgent.getObjectSize(object) + ” bytes.”);
}

/**
* Main executable function.
*
* @param arguments Command-line arguments; none expected.
*/
public static void main(final String[] arguments)
{
final StringBuilder sb = new StringBuilder(1000);
final boolean falseBoolean = false;
final int zeroInt = 0;
final double zeroDouble = 0.0;
final Long zeroLong = 0L;
final long zeroLongP = 0L;
final Long maxLong = Long.MAX_VALUE;
final Long minLong = Long.MIN_VALUE;
final long maxLongP = Long.MAX_VALUE;
final long minLongP = Long.MIN_VALUE;
final String emptyString = “”;
final String string = “ToBeOrNotToBeThatIsTheQuestion”;
final String[] strings = {emptyString, string, “Techsivam”};
final String[] moreStrings = new String[1000];
final List someStrings = new ArrayList();
final EmptyClass empty = new EmptyClass();
final BigDecimal bd = new BigDecimal(“999999999999999999.99999999″);
final Calendar calendar = Calendar.getInstance();

printInstrumentationSize(sb);
printInstrumentationSize(falseBoolean);
printInstrumentationSize(zeroInt);
printInstrumentationSize(zeroDouble);
printInstrumentationSize(zeroLong);
printInstrumentationSize(zeroLongP);
printInstrumentationSize(maxLong);
printInstrumentationSize(maxLongP);
printInstrumentationSize(minLong);
printInstrumentationSize(minLongP);
printInstrumentationSize(maxLong);
printInstrumentationSize(maxLongP);
printInstrumentationSize(emptyString);
printInstrumentationSize(string);
printInstrumentationSize(strings);
printInstrumentationSize(moreStrings);
printInstrumentationSize(someStrings);
printInstrumentationSize(empty);
printInstrumentationSize(bd);
printInstrumentationSize(calendar);
printInstrumentationSize(Color.WHITE);
}
}

 

build.xml

  • using this ant create the Instrumentation.jar

<?xml version=”1.0″ encoding=”UTF-8″?>
<project name=”MyTest” default=”jar” basedir=”.”>
<target name=”jar”
description=”Package compiled classes into JAR file”
depends=”compile”>
<jar destfile=”Instrumentation.jar”
basedir=”..\bin”
filesonly=”${jar.filesonly}”>
<manifest>
<attribute name=”Premain-class”
value=”techsivam.examples.InstrumentationAgent”/>
<attribute name=”Agent-class”
value=”techsivam.examples.InstrumentationAgent”/>
</manifest>
</jar>
</target>

<!– Compiles the java code –>
<target name=”compile” depends=”clean, makedir”>
<javac srcdir=”.” destdir=”..\bin” classpathref=”.classpath” />
</target>
<!– Deletes the existing bin directory–>
<target name=”clean”>
<delete dir=”${bin.dir}” />
</target>

<!– Creates the bin directory–>
<target name=”makedir”>
<mkdir dir=”${bin.dir}” />
</target>
</project>

 

 

RUN:

  • once jar is created go to command line and run the following command

C:\Users\TechSivam\JAVAworkspace1\MyTest\src>java -javaagent:Instrumentation.jar
-cp Instrumentation.jar techsivam.examples.InstrumentSampleObjects
premain…
Object of type ‘class java.lang.StringBuilder’ has size of 16 bytes.
Object of type ‘class java.lang.Boolean’ has size of 16 bytes.
Object of type ‘class java.lang.Integer’ has size of 16 bytes.
Object of type ‘class java.lang.Double’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.Long’ has size of 16 bytes.
Object of type ‘class java.lang.String’ has size of 24 bytes.
Object of type ‘class java.lang.String’ has size of 24 bytes.
Object of type ‘class [Ljava.lang.String;’ has size of 24 bytes.
Object of type ‘class [Ljava.lang.String;’ has size of 4016 bytes.
Object of type ‘class java.util.ArrayList’ has size of 24 bytes.
Object of type ‘class techsivam.examples.EmptyClass’ has size of 24 bytes.
Object of type ‘class java.math.BigDecimal’ has size of 32 bytes.
Object of type ‘class java.util.GregorianCalendar’ has size of 112 bytes.
Object of type ‘class techsivam.examples.InstrumentSampleObjects$Color’ has size of
16 bytes.

 





Singleton In Clustered Environment

11 08 2014
  • Singleton is very important and familiar design pattern in java
  • it will work very well in single JVM
  • but in application is using  multiple JVM, how do we achieve single instance for the object of the class?

To Achieve in multiple JVM in clustering environment we can use

  • JMS
  • DB – when we use multiple JVM, if that’s shares common db, we can check through the DB entry.
  • 3rd party tools like Oracle Coherence 




Java Singleton Design Pattern

11 08 2014
  • we can create singleton in different ways depending on the requirement/situation.
  • In Java Singleton Pattern is used to create only one instance of the particular class in the application.

 

  • Singleton Eager Initialization
  • This Approach object will initialize in the starting of the application itself.
  • so unnecessary object will be initialized even if we are not using that singleton class

/**
* @author TechSivam
* This class is for Singleton Eager Initialization Example
*/
public class SingletonEagerInitialization {

// static final member variable
private static final SingletonEagerInitialization INSTANCE = new SingletonEagerInitialization();

// private constructor
private SingletonEagerInitialization() {
}
// public static method to get the instance.
public static SingletonEagerInitialization getInstance() {
return INSTANCE;
}
}

  • Singleton Lazy Initialization
  • in this approach when we use this singleton class , only that time it will create object, otherwise it will not create object.

/**
* @author TechSivam
* This class is for Singleton Lazy Initialization Example
*/
public class SingletonLazyInitialization {
// static member variable
private static SingletonLazyInitialization INSTANCE;

// private constructor
private SingletonLazyInitialization() {
}

// public static method to get the instance.
public static SingletonLazyInitialization getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingletonLazyInitialization();
}
return INSTANCE;
}
}

  • Singleton Thread Safe
  • in this approach when we use this singleton class for multi threading environment , only one instance will create.
  • we need to synchronized the get method.

/**
* @author TechSivam
* This class is for Singleton Thread Safe Example
*/
public class SingletonThreadSafe {
// static member variable
private static SingletonThreadSafe INSTANCE;

// private constructor
private SingletonThreadSafe() {
}

// public synchronized static method to get the instance.
public synchronized static SingletonThreadSafe getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingletonThreadSafe();
}
return INSTANCE;
}
}

  • Singleton with Serializable
  • when we are using networking application, we are passing serialized object through network we need to use this approach

 

/**
* @author TechSivam
* This class is for Singleton with Serializable Example
*/
public class SingletonWithSerializable implements Serializable {
private static final long serialVersionUID = -5669370075648474485L;
// static member variable
private static SingletonWithSerializable INSTANCE;

// private constructor
private SingletonWithSerializable() {
}

// public static method to get the instance.
public static SingletonWithSerializable getInstance() {
if (INSTANCE == null) {
INSTANCE = new SingletonWithSerializable();
}
return INSTANCE;
}
}

  • Singleton Enum
  • by default its thread safe

/**
* @author TechSivam
* This is Enum class, by default it is singleton and thread safe
*/
public enum SingletonEnum {

INSTANCE;

public static void doSomething(){
//do something
}
}





My SQL Storage Engine InnoDB VS MyISAM

8 08 2014
*************************** InnoDB  ***************************
      Engine: InnoDB
     Support: DEFAULT
     Comment: Supports transactions, row-level locking, and foreign keys
Transactions: YES
          XA: YES
  Savepoints: YES
*************************** MyISAM    ***************************
      Engine: MRG_MYISAM
     Support: YES
     Comment: Collection of identical MyISAM tables
Transactions: NO
          XA: NO
  Savepoints: NO

InnoDB  :

The default storage engine in MySQL 5.7. Supports ACID, row level locking , Mostly used for Write/Update/Delete Operations.

MyISAM   :

Table level locking

supports for Fast Read from DB.

 

 





How to Prevent Child class from Serialization in Java

8 08 2014

We have parent class which is serializable, but child class we should not allow serializable. for this we can writeObject,readObject API’s throw NotSerializableException Exception in Child Class.

1) Parent Class

public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public String address;
}

2) Child Class

public class Child extends Parent implements Serializable {

public Integer aadhar;
public Integer id;

private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}

private Object readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
throw new NotSerializableException();

}

}

3) Serialize Implementation Example 

public class SerializeEx {
public static void main(String[] args) {
Child e = new Child();
e.name = “Siva”;
e.address = “Bangalore”;
e.aadhar = 11122333;
e.id = 101;
try {
FileOutputStream fileOut = new FileOutputStream(“child.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf(“Serialized data is saved in child.ser”);
} catch (IOException i) {
i.printStackTrace();
}
}
}

4) Error:

Wile Running this program:

java.io.NotSerializableException

at com.ts.test.serli.Child.writeObject(Child.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.ts.test.serli.SerializeEx.main(SerializeEx.java:17)








Follow

Get every new post delivered to your Inbox.

Join 1,502 other followers

%d bloggers like this: