Archive for January, 2014

Start carbon servers with OSGI console

./wso2server.sh -DosgiConsole

You will see below are the set of commands that are currently available

—Server Admin (WSO2 Carbon)—
listAdminServices – List admin services deployed on this Carbon instance
listHiddenServices – List hidden services deployed on this Carbon instance
listSystemServicesInfo – List all the systems services deployed on this Carbon instance
dumpAdminServices – Dump all the wsdls of admin services on this Carbon instance
restartCarbon – Forcefully restart this Carbon instance
restartCarbonGracefully – Gracefully restart this Carbon instance. All client connections will be served before restarting the server
shutdownCarbon – Forcefully shutdown this Carbon instance
shutdownCarbonGracefully – Gracefully shutdown this Carbon instance. All client connections will be served before shutting down the server
startCarbonMaintenance – Switch a Carbon instance to maintenance mode.
endCarbonMaintenance – Change the state of a Carbon instance from “maintenance” to “normal”

However you may want to add a command of your own. It may be helpfull for you to view runtime data.

Add a custom command
Write the command  class

You are required to implement org.eclipse.osgi.framework.console.CommandProvider interface in order to add a command of your own. You need to implement

String getHelp()This return the help text of the command which will be showned when you type “help customCommand”.Now comes your command. You must add a public method with void as the return type and method name must start with the _(underscore) before the name of the command. Method argument must be “org.eclipse.osgi.framework.console.CommandInterpreter” type. As an example if I want to add a “sayHello” command, my method is like below.public void _sayHello (CommandInterpreter ci)

package org.apache.stratos.autoscaler.commands;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;

public class EchoCommand implements CommandProvider{

public String getHelp() {
return "\necho - echoes the String provided. \n" + "\t parameters : \n" + "\t\t String text to be echoed.\n";
}
public void _echo(CommandInterpreter cli){
String text = ci.nextArgument();
cli.println(text);
}
}

nextArgument() gets the argument the user has given with the command (Ex “echo hellowWorld”)
println prints the text in the console.

Register the new service in OSGI

The below code will inform the OSGI framework about the new command class.

package org.apache.stratos.autoscaler.internal;
public class CommandBundleActivater implements BundleActivator{

private static final Log log = LogFactory.getLog(CommandBundleActivater.class);

@Override
public void start(BundleContext context) throws Exception {
if(log.isDebugEnabled())
log.debug("AutoScaler bundle is activated.");

context.registerService(CommandProvider.class.getName(),new EchoCommand(), null);
}
}
Add the bundle activater

Now add the foloowing lines to the required pom.xml file, so

<Bundle-Activator>org.apache.stratos.autoscaler.internal.CommandBundleActivater</Bundle-Activator>

Below are the output of the command.

osgi> help echo

echo - echoes the String provided.
 parameters :
 String text to be echoed.

osgi> echo HellowWorld
HellowWorld
Advertisements

Singleton pattern inside out using Java

Posted: January 15, 2014 in linux, ubuntu
Tags: , ,
  • Naive approach

Singleton is a software design pattern which ensures only one object of a type is created. This is useful in when we want to create an object which manages or co ordinates some tasks in the system.

private static Singleton instance = null;
protected Singleton() {
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}

The call to Singleton.getInstance() will create a new Singleton type object if the varirable “instance” is null and return it, if “instance” is not null getInstance() just return the “instance”.
The variable “instnace” which is null at the startup is assigned an object at the first call to Singleton.getInstance(), subsequent call to Singleton.getInstance() return the object created at the first call.
Thus ensures only one object of Singleton is there no matter the number of time the getInstance() is called.
This works as expected in a single threaded environment, if only one thread calls getInstance(). If there are multiple threads say A and B, thread A may reach at the null check at which point thread B start executes.
At this point instance is still null to the thread A. Now thread B executes null check the instance and create a new Singleton. Then thread a again executes and create another Singleton since
instance is still null for A. So if there are multiple thread accessing the Singleton class, above code does not ensures the Singletoness.

  • Multi threaded approach.

In order to solve the problem mentioned above, we have to make sure only one thread accesses the getInstance() at a moment. The solution to ensure mutual exclusion for threads in Java is synchronizing the getInstance().

class Singleton {
private Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

The above methods works and provide singletonness. However there is a performance issue. Each and every call need to execute synchronized block which slows down the execution.
In a environment where get instance() is called frequently this will cause a considerable performance degrade.

  •  Double check approach

Double check is introduced to avoid above performance hit. It Go inside synchronized block only after performing instance null check. If it is not null it won’t go inside synchronized block.

class Singleton {
private Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

Double check may also cause problems due many reasons, compiler optimization is one of them. Instance = new type() seems just one operation for us. But there are multiple  operations hidden inside. They are a locating memory for the instance, creating the new object by calling the constructor, assigning the newly created object to the “instance” reference. The compiler optimization may reorder these operations depending on the compiler implementation.

Step 1) Assign object to the “instance” reference

Step 2) Constructor code
If the compiler order in above way, if another thread start executed get instance() it may see the instance as Not null (since step1 is over) but only see the default values of the attribute s of the object, not the values specified in the constructor. So the other objects get the wrong values.

  • Make instance volatile
class Singleton {
private volatile Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

By making the instance variable volatile above issue can be resolved since  partial values of volatile variables are not visible to other threads.

  •  A better solution with java class loading(lazy initialization)
    class Singleton {
    private static class InstanceHolder {
    public static Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance() {
    return InstanceHolder.instance;
    }
    }
    

JVM guarantees a class is loaded only once. We add a inner class to store the instance. Since instance is static it is initialized at the time of class loading, thus guaranteed only one instance is created since class is loaded only once. One important thing to notice is InstanceHolder inner class is loaded only at the first call to getinstance(), so delay the instance creation until the object is needed which we call lazy initialization.