Wednesday, December 30, 2009

MBean Descriptors

JMX MBean/MXBean get accessed by different clients(Ex: JConsole, VisualVM, and etc.,), where it is our responsibility that to explain/descirbe the details of the Bean, it includes

  • MBean author, version and etc.,
  • Attribute display name, type, minValue, maxValue, defaultValue and recommendedValue and its behaviour
  • Operation display name, and its argument details

Java SE 6 has come up integrated way of annotation approach for all types of MBean, where we can specify the additional details, is called Descriptors.

Author.java
package com.example.mxbeans; 
 
import java.lang.annotation.Documented; 
import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 
import javax.management.DescriptorKey; 
 
@Documented 
@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Author { 
    @DescriptorKey("Author") 
    String value(); 
} 

HelloWorldMXBean.java

package com.example.mxbeans; 
 
@Author("Krishna")
public interface HelloWorldMXBean { 
    @DisplayName("GETTER: Name") 
    public QueueSample getName(); 
    @DisplayName("OPERATION: clearHelloCount") 
    public void clearCount(); 
} 

In runtime these metadata/annotation converts in to JAVA object, for most constructors in the classes MBean*Info (MBeanInfo, MBeanAttributeInfo, and so on), a parallel constructor exists with the same parameters plus an additional javax.management.Descriptor parameter. The same is true for OpenMBean*InfoSupport. The MBean*Info and OpenMBean*InfoSupport classes contain a getDescriptor() method.

Read: MBean Descriptors Tutorial

Resource Injection

Singleton Class

Singleton Class is created to maintain only one instance of this class object made available for application's ClassLoader. To achieve this, we have to add restrictions for this class access

  • All Constructors has to have private as access modifier
  • One factory pattern based, means atleast one public static method defined to create instance of this class
  • One static variable defined to hold this singleton object
  • Factory method has to be implemented gurantteing to not to create instance more than once.
    
    public static SingletonClass getInstance(){
    if(null == ins1)
    {
    ins1=new SingletonClass();
    }
    return ins1;
    }
  • To achieve thread safe, this getInstance() method has to use synchronized in method.

Singleton offers lots of advantage in creating instance in Application Context. In multi-threaded environment, if this synchronized getInstance() method called parallely then performance will be beaten heavily. Instance creation happens very early start up time of application, once object instanciated, then we have to avoid this if check and synchronized block execution. How to synchronized block in singleton class object instanciation ?

To answher the above question, we have to assign getInstance() result to the above mentioned static variable.

public static SingletonClass ins = getInstance();

However, this instance has to be initialized based on the argument passed then this could be painful job in creating instance and making it thread safe. Even we can build additional logic to achieve this, however, if an application comes with more number of singleton objects and Object lifecycle also be clearly maintained or controlled, then it is really more pain. We will end up spending time in this logic rather than in real business of application. Various tools available in market to provide application infrastructure runtimes. Eg: SpringSource

Java Enterprise Edition 5

Java EE 5 comes with Resource Injection concept, offers ease way of assigning object reference to the fields in a Class.

  • JSR 250 - Common annotations: Common Annotations for the Java Platform Specification, provides the semantics of the platform's common annotations.
  • JSR 220 - EJB beans: the Enterprise JavaBeans 3.0 Specification, Section 8.1, Annotation of Context Dependencies.
  • JSR 224 - Web services: the Java API for XML-Based Web Services (JAX-WS) 2.0 Specification, javax.xml.ws.WebServiceRef.
  • JSR 255 - JMX 2.0, Remote API for JMX, uses JSR 250 common annotations

public static DataSource catalogDS=null;
public synchronized javax.sql.DataSource getCatalogDS() {
try {
 if(null == catalogDS)
 {
  // Obtain the initial Java Naming and Directory Interface
  // (JNDI) context.
  InitialContext initCtx = new InitialContext();
  // Perform JNDI lookup to obtain the resource.
  catalogDS = (DataSource)
  initCtx.lookup("java:comp/env/jdbc/catalogDS");
  }
 } catch (NamingException ex) {
 // Handle failure.
 }
 return catalogDS;
}
 ...
public getProductsByCategory() {
    // Get the DataSource.
    DataSource catalogDS = getCatalogDS();
    // Get a connection and execute the query.
    Connection conn = catalogDS.getConnection();
    ...
}
In web.xml:
<resource-ref>
    <description>Catalog DataSource</description>
    <res-ref-name>jdbc/catalogDS</res-ref-name>
     <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

In the above code, getCatalogDS() will be called DAO design pattern methods to get a connection from DataSource. Establishing or making available this DataSource resource to the application mostly one time job in nature. But here in the above code, getCatalogDS() called everytime methods in DAO Class called.

In web Application, all possible resources are defined in web.xml with resource type. The same will be accessed from application like the way in sample code. Using resource injection, we can achieve this by placing annotation above the field


private @Resource DataSource catalogDS;

public getProductsByCategory() {
    // Get a connection and execute the query.
    Connection conn = catalogDS.getConnection();
    ...
}

No additional details required to be mentioned in web.xml. If we have multiple Datasource resource mentioned in web.xml, then we need to specify additional details in @Resource annotation.

Common annotations
  • @Resource
  • @Resources
  • @DeclaresRoles
  • @RunAs
  • @PostConstruct
  • @PreDestroy
EJB beans
  • @PersistenceContext
  • @PersistenceContexts
  • @PersistenceUnit
  • @PersistenceUnits
Web services
  • @WebServiceRef
  • @WebServicesRefs

Refer TechNote

JMX 2.0 API: MBeanRegistration

javax.management.MBeanRegistration interface allows user to perform pre or post MBeanServer registration or unregistration. We can achieve this by making resource injection. Right now, this available only for the class or subclass of MBeanServer, ObjectName, or SendNotification in JMX 2.0 API.


public Configuration implements ConfigurationMBean {
 @Resource
 private volatile MBeanServer mbeanServer;
 @Resource
 private volatile ObjectName objectName;
 ...
 void unregisterSelf() throws Exception {
  mbeanServer.unregisterMBean(objectName);
 }
 
 @Resource
 private volatile SendNotification sender;
 ...
 private void updated() {
  Notification n = new Notification(...);
  sender.sendNotification(n);
 }
 
 @Resource(type = MBeanServer.class)
 private volatile MBeanServerConnection mbsc;
 }

Note: A field to be injected must not be static. It is recommended that such fields be declared volatile.

Tuesday, December 29, 2009

StuckThread Exception

In Application server, mangaged/unmanaged threads can run continuously without interrupting/sleep/wait for a given/sliced time. If the thread exceeds the maximum time configured for StuckThreadMaxTime.

Server keeps the track of when the thread started and how long continuously running, once the thread exceeds time immediatly the respective thread state will changed to STUCK and incident error will be thrown. However, thread will be kept running. Hence, we can consider this as benign error message.

Administrator can take call on based on how many times, this issue comes in a day, and what is the sevearity of this issue giving thread.

Each application server has the provision to configure the max time. We may have a question, why this limitation is required for Server? , this limitation needed for security reasons. Assume that, we have deployed a web application where HTTP call made by crackers/hackers to stop responding application for intented customer by keeping server always busy. Server helps us by notifying server panic state by throwing this error message.

In weblogic, default value for stuckThread Max Time would be 600s.

Environment > servers > soa_server > Configuration > Tuning > change Stuck Thread Max Time

This value has to be changed only when we get stuck thread exception and increasing this number may degrade performance. Maximum 1200s would be the recommended value for weblogic server.


<Apr 3, 2009 4:30:26 PM PDT> <Error> <WebLogicServer> <BEA-000337> <[STUCK] 
ExecuteThread: '1' for queue: 'weblogic.ker 
nel.Default (self-tuning)' has been busy for "1,301" seconds working on the 
request "org.bank.BankUtilityBean_fq50_EOImpl", which is more than the 
configured time (StuckThreadMaxTime) of "1,200" seconds. Stack trace: 
java.net.SocketInputStream.socketRead0(Native Method) 
java.net.SocketInputStream.read(SocketInputStream.java:129) 
oracle.net.ns.Packet.receive(Packet.java:240) 
oracle.net.ns.DataPacket.receive(DataPacket.java:92) 
oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:172) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:117) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:92) 
oracle.net.ns.NetInputStream.read(NetInputStream.java:77) 
oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1034) 
oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1010) 
oracle.jdbc.driver.T4C8TTILob.receiveReply(T4C8TTILob.java:847) 
oracle.jdbc.driver.T4C8TTILob.write(T4C8TTILob.java:243) 
oracle.jdbc.driver.T4CConnection.putBytes(T4CConnection.java:2078) 
oracle.sql.BLOB.setBytes(BLOB.java:698) 

Saturday, December 26, 2009

MBean vs MXBean

MBean vs MXBean

Manageable Resources are identified and instrumented as java objects, it could be Managed Bean(MBean) or advanced/extended/simplified Managed Bean(MXBean).

Managed Bean

MBeans can be any of java objects, in which we can store/retrive Serializable/Externalizable objects using methods. Based on the design pattern used in objects, we can differentiate either Standard(static) or Dynamic. Recommended to maintain Interface class name suffixed with MBean
Standard MBeans
Java objects that conform to certain design patterns derived from the JavaBeans component model.
  • fields are declared with access modifier as private, setter and getter methods with access modifier public, is called Attributes
  • Additionally, methods declared with access modifier public to do special operations, is called operations

public interface HelloWorldMBean {
//attributes
public String getName();
public void setName();

//operations
public void clearHelloCount();
public String sayHello(String name);
}
Dynamic MBeans
javax.management.DynamicMBean interface that offers more flexibility at runtime.
  • Object getAttribute(String attribute)
    Obtain the value of a specific attribute of the Dynamic MBean.
  • AttributeList getAttributes(String[] attributes)
    Get the values of several attributes of the Dynamic MBean.
  • MBeanInfo getMBeanInfo()
    Provides the exposed attributes and actions of the Dynamic MBean using an MBeanInfo object.
  • Object invoke(String actionName, Object[] params, String[] signature)
    Allows an action to be invoked on the Dynamic MBean.
  • void setAttribute(Attribute attribute)
    Set the value of a specific attribute of the Dynamic MBean.
  • AttributeList setAttributes(AttributeList attributes)
    Sets the values of several attributes of the Dynamic MBean.
Sample:
//Registering MBean in server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=HelloWorld");
Object mbean = new HelloWorld();
mbs.registerMBean(mbean, name);

//Retrieving MBean from server
HelloWorldMBean hwBean = JMX.newMBeanProxy(mbs, name, HelloWorldMBean.class);
hwBean.sayHello("JMX");

MXBean

MXBeans reference only a pre-defined set of types. Recommended to maintain Interface class name suffixed with MXBean. Implements interface of Dynamic or cusotmized JavaBean. Using MXBean, We can facilitate any client to use MBeans. Additional details required to use MXBean

  • In interface, Class name has to be suffixed with MXBean or annotation @MXBean has to be used.
  • In implementation class, annotation ConstructorProperties used to reconstruct the MXBean in retrievel time. Possible attribute names required to get from MBeanServer for this ObjectName has to be listed in constructor argument.
  • No Model-Class implementation not required to retrive pre-defined types.
  • CompositeData used to reconstruct Complex Objects.

However, in implementation class, annotation used to specify the attribute details in ConstructorProperties. And, In discovering and accessing code has the differences. Instead of directly retrieving the cusomer defined Bean, javax.management.openmbean.CompositeDataSupport has used to retrieve the data.



Sample:

public HelloWorld implements HelloWorldMXBean{
private String name;
@ConstructorProperties({"name"})
public HelloWorld(String name)
{this.name=name;
}
}

...

//Registering MXBean in server
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=HelloWorld");
Object mbean = new HelloWorld();
mbs.registerMBean(mbean, name);

//Retrieving MXBean from server
//Predefined type retrieval
 String nameAttribute=mbs.getAttribute(name, "name");
 
//using CompositeData for complex java objects
CompositeData userdefinedBean = (CompositeData) mbs.getAttribute(name, "ComplexJavaObject");
String name = (String) hwBean.get("name");

//using proxy
HelloWorldMXBean proxy = JMX.newMXBeanProxy(mbs, name, HelloWorldMXBean.class);

Refer:
In java.net, What is an MXBean ? blog by Eamonn McManus.

IOException: Broken pipe

java.io.IOException: Broken pipe

In Client server application, Message send from/to. If message size is less than 10MB, then we would have not faced any issues. Since most of the application/web server comes with default configuration for message size to 10MB or more.

Usecase : upload a zip file from client to server

In server side, any of the endpoints like Servlet(http), EJB, JMS, or TCP, has to be established to receive message as byte array or byte array holding java objects. Stream objects can not be serialized, it has to be stored as byte and trasmitted. While marshalling and unmarshalling byte array object, Heap usage go to the peak. In this time, we may get OutOfMemoryException

In Client Side, InputStream created to read data from file and convert into byte array.

If server receives message more than the size configured then server will throw weblogic.socket.MaxMessageSizeExceededException

<ExecuteThread: '1' for queue: 'weblogic.socket.Muxer'> <<WLS Kernel>> <> <> <1229479358244> 
<BEA-000403> <IOException occurred on socket: Socket[addr=/127.1.1.34,port=281 30,localport=8001] 
weblogic.socket.MaxMessageSizeExceededException: Incoming message of size: '10000080' bytes 
exceeds the configured maximumof: '10000000' bytes for protocol: 't3'.>
at weblogic.socket.BaseAbstractMuxableSocket.incrementBufferOffset(BaseAbstractMuxableSocket.java:174)
at weblogic.rjvm.t3.MuxableSocketT3.incrementBufferOffset(MuxableSocketT3.java:343)
at weblogic.socket.SocketMuxer.readReadySocketOnce(SocketMuxer.java:906)
at weblogic.socket.SocketMuxer.readReadySocket(SocketMuxer.java:842)
at weblogic.socket.JavaSocketMuxer.processSockets(JavaSocketMuxer.java:335)
at weblogic.socket.SocketReaderRequest.run(SocketReaderRequest.java:29)
at weblogic.work.ExecuteRequestAdapter.execute(ExecuteRequestAdapter.java:21)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:145)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:117)

If server receives message even with in the limit, but while unmarshalling data, application exceeds heap size, then server will drop the connection established with client abrubtly with OutOfMemoryException. Since connection got closed then we do get IOException as below.

java.io.IOException: Broken pipe
at java.net.SocketOutputStream.socketWrite(Native Method)
at java.net.SocketOutputStream.write(SocketOutputStream.java:83)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:72)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:130)
at java.io.FilterOutputStream.flush(FilterOutputStream.java:123)
at weblogic.net.http.ContentLengthOutputStream.close(ContentLengthOutputStream.java:56)


Note:Broken pipe message comes for anytime stream could not able to write/read data from file(socket). In general, heart beat will be delivered by server/client in stipulated format. If this max number of attempts cross then application assumes that socket is closed by other party and throws this exception.


Weblogic

In weblogic server console or config xml, we can set maximum message size only to the http protocol or t3 or all the protocols.

Environment > servers > soa_server > protocols > General > change Maximum Message Size as below

<max-message-size>100000000</max-message-size>
<max-t3-message-size>100000000</max-t3-message-size>
<max-http-message-size>100000000</max-http-message-size>
The above code set 100mb for these properties. These configuration helps to intimate the server that maximum message of receiving capacity. There is no configuration required to be configured to send message from server.

What about client side, to receive 100 mb message?

Yes, we have to set weblogic.MaxMessageSize config property in commandline.

-Dweblogic.MaxMessageSize=100000000


Refer this link supported maximum message size in weblogic

Java Management Extensions (JMX)

Java Management Extensions (JMX)

Application is running for a long time suddenly started performing not good. We do not have any clue at this time. Idea started early 1998, there should be a way to interact the application from a local/remote vM to monitor and maintain the resource. For example, HeapSize almost reached maxSize and full collector not yet triggered, in this time we could make a request for GC from our application. This may not be the right solution, however, we can avoid OOM Exception.

In clustered environment, application may share the same configuration. User may update property in one node, which has to be replicated in other environment in flexible way. We cannot use tightly coupled model, since in failover scenario this will cause more pain to us. JMX Remote API, solves this problem by Change notification mechanism.

JSR details:

  • JSR 3 - Java Management Extensions
  • JSR 160 - JMX Remote API
  • JSR 255 - JMX 2.0


Typical uses of the JMX technology include:

  • Consulting and changing application configuration
  • Accumulating statistics about application behavior and making them available
  • Notifying of state changes and erroneous conditions.

The resources are instrumented as JAVA Object, known as Managed Beans(MBean). MBeans and its services sare registered in a Object Server, known as MBean Server or JMX agents. JMX Connectors helps agent to connect remote VM.

  • enables Java applications to be managed without heavy investment
  • provides a standard way to manage Java technology-based applications, systems, and networks
  • can be used for out-of-the-box management of the Java VM
  • provides a scalable, dynamic management architecture
  • leverages existing standard Java technologies
  • integrates easily with existing management solutions and emerging technologies. JMX solutions can use lookup and discovery services and protocols such as JiniTM network technology and the Service Location Protocol (SLP).

Examples TechNote

Friday, December 25, 2009

JNDI Environment Properties

JNDI Environment Properties

JNDI provides place to specify various configuration details. There are different types of environment properties and defined in four clauses.


Standard JNDI environment properties
- defined by JNDI and common in all the service providers
  • java.naming.provider.url - URL, where the service provider deployed
  • java.naming.factory.initial - Initial Context implemented Class
  • java.naming.dns.url - URL, DNS host and domain names to use for the "jndi" URL context implementation
  • java.naming.factory.object
  • java.naming.factory.state
  • java.naming.factory.control
  • java.naming.factory.url.pkgs
Service-Specific Environment Properties
Common across all the service providers. Properties have the prefix java.naming.service. . For instance, java.naming.ldap.
Feature-Specific Environment Properties
Common across all the service providers for particular feature. Properties have the prefix java.naming.feature. . For instance, java.naming.sasl.
  • java.naming.security.principal - username
  • java.naming.security.credentials - password (if keystore configured then key will be placed here instead of password)
Provider-Specific Environment Properties
Specific to service provider. For instance, LDAP trace property com.sun.jndi.ldap.trace.ber, GSS-API and kerberos properties java.security.auth.login.config=gsseg_jaas.conf java.security.krb5.conf=krb5.conf

Some useful links Tutorial,TechnotessSecurity/Permission in client



Sample code to get context from LDAP


Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:7009/o=Oracle");

Context ctx = new InitialContext(env);

Thursday, December 24, 2009

Oracle JRockit : OutOfMemoryError

Oracle JRockit : OutOfMemoryError

Thread Local Area and LargeObjectOrArray


In JRockit, Each thread allocates TLA (Thread Local Area) to store short living objects, and benefits GC to reclaim space. The repective thread can then allocate
objects in its TLA without synchronizing with other threads. If particular TLA size become full, then new TLA will be alotted. In general, we think that by specifying bigger number for TLA we get best performance. But reality is not that case, whenever new thread starts, TLA size has to be reserved with minimum space mentioned in tlasize.



We can specify what could be the largeObject or Array size needs to be stored in TLA, others goes to Heap. Recommendation would be, -XXtlasize:min and -XXlargeObjectLimit has to be equivalent and -XXtlasize:preferred size must to set minimum double the -XXlargeObjectLimit value.



-XXtlasize:min=3k -XXtlasize:preferred=10k -XXlargeObjectLimit=3k

Above configuration tells JVM that 3k objects are larger and it should not go to TLA. Each TLA can grow maximum 10k. If application starts/maintains maximum of 100 threads and all operates on its own data (mean, no synchronization required), then specifying bigger number for TLA, would help to increase the application.



Exception in thread "PoolThread" java.lang.OutOfMemoryError: allocLargeObjectOrArray - Object size: 586154000, Num elements: 586153984
Cause: allocLargeObjectOrArray - Object size: 65552, Num elements: 32768



In the above exception Object Size specifies the size of the Object trying to store in old space with Num elements. This is due to poor garbage collection triggered.



Nursery Size


-Xns option used to specify the size of Nursery. Garbage collection happens quickly in Smaller nursery and larger size takes longer. This size has to be defined based on the application memory usage, and eventually it is Performance Engineer responsibility to set memory settings to make sure that as many object as possible are garbage collected by young collection rather than old collection.Recommended value for this size would be half of the free heap size.



-Xns=100m

-XXkeepAreaRatio:<percentage> used to keep the young and old collection frequency. If ratio high young generation will be triggered often.



Garbage Colletor


JRockit R27.3.0 and later releases offers various types of collector. It is our responsibility to find best suiting option to our application.




Static garbage collector


-Xgc:<strategy>
-Xgc:genpar - generational parallel garbage collector
-Xgc:gencon - To use a generational concurrent garbage collector

-Xgc:singlecon - To use a single-spaced concurrent garbage collector
-Xgc:singlepar - single-spaced parallel garbage collector


Dynamic garbage collector


-XgcPrio:<mode>
-Xgcprio:throughput - gives priority for throughput
-XgcPrio:pausetime -XpauseTarget=40ms - gives priority for pause time
-XgcPrio:deterministic -XpauseTarget:40ms - gives priority for throughput and not crossing pause time


Parallel Mark and Sweep

While garbage collection other Java threads will be paused- genpar and singlepar.



Mostly Concurrent Mark and Sweep

While garbage collection all other JAVA threads will not be paused, if no necessary of synchronization - singlecon and gencon.



For more details, visitOracle JRockit

Wednesday, December 23, 2009

TCP Monitoring

TCP Monitoring

Network programming may be direct low level TCP communication or high level like RMI, HTTP, Web services, and etc., we may need to debug the message what and how it delivers in TCP layer. This will help us to debug and dig to chase the right tail. Sometime, we may see data incorrectly in receiving end due to network issues and we will start correcting our implementaion in server and client.

tcpmon is an open-source utility to Monitor A TCP Connection. In which, we can see the TCP layer data goes out of the box and also the response comes from the server. I have started using this tool to understand the structure of the SOAP message and HTTP headers. Specifically while going with encryption like MTOM/XOP, this tool helped lot.

If you want to count or see the content get transmitted while using browser to connect web application also, this tool helps lot.

We have to place this tool in between the server and client. For instance, I have to connect to application http://www.javafundu.com:7001/checkTCP. Here are the steps


  1. Double click the downloaded tcpmon.jar from tcpmon.dev.java.net
    or run command java -jar tcpmon.jar

  2. In Create a New TCP Monitor connection, set Local port=8080, Server Name=javafundu.com, and Server Port=7001

  3. Click on Add Monitor. Now TCP monitoring started

  4. Start the browser, and type the URL as http://localhost:8080/checkTCP

  5. Now Request from browser and response of the same also captured in TCPMon and get displayed.




Tuesday, December 22, 2009

Resolving Objects in Deserialization

Resolving Objects in Deserialization

Customer has send the data as serialized object to us, where as I am not interested in all the data or the class which serialized, or I have to create a class in which I can add aditional data in it.


We could do this operation by fetching the object and handing over to some method to create a new Object from it. It is painstaking job, and will not produce nice implmentation approach


We can achive resolving object by creating sub-class for ObjectInputStream with overriding method resolveObject(Object). In this method, we can do our business related sutff and get the objected wanted while deserializing




Example



I have created sub-class MyObjectInputStream from ObjectInputStream and override the resolve method. Note: resolveObject() method will not be called until unless the resolveObject flag set to true by calling method enableResolveObject(true);. I am setting this value true in constructor of the MyObjectInputStream class.





import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class DeserializeTest {

public static class EmployeeBean implements Serializable
{
String name;
String designation;
}

private static class MyObjectInputStream extends ObjectInputStream
{
public MyObjectInputStream(InputStream in) throws IOException {
super(in);
enableResolveObject(true);
}

@Override
protected Object resolveObject(Object obj) throws IOException {
if (obj instanceof EmployeeBean) {
EmployeeBean new_name = (EmployeeBean) obj;
StringBuffer sb=new StringBuffer();
sb.append(new_name.name);
sb.append(" ");
sb.append(new_name.designation);
return sb;
}

return super.resolveObject(obj);
}
}

/**
* @param args
*/
public static void main(String[] args) throws Exception{
EmployeeBean emp=new EmployeeBean();
emp.name = "Krishna";
emp.designation="PMTS";
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream out= new ObjectOutputStream(bos);
out.writeObject(emp);

ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
MyObjectInputStream in= new MyObjectInputStream(bis);
Object obj=in.readObject();
System.out.println(obj);
}
}


The Output will be like below

Krishna PMTS



In the above program comment enableResolveObject(true); line and try, the output will be the Object reference of EmployeeBeen; Something like below

ObjectStreamClassTest$EmployeeBean@10b30a7



Note: Playing with ObjectInputStream ,ObjectOutputStream, and ObjectStreamClass, we can do lot and control the content of serialized stream.

ObjectStreamClass

ObjectStreamClass



java.io.ObjectStreamClass class implements Serializable interface and it describes the details of JAVA classes. ObjectStreamClass plays major role in serialization, it offers us to know about

  • getName() - Class Name
  • getSerialVersionUID() - serialVersionUID
  • getFields()- fields and its type
  • forClass() - returns class in local JVM
  • lookup(Class<?> cl)/lookupAny(Class<?> cl) - used to get Classdescribtor object for particular class



Since this class offers to know about data phase of class, it will be useful in various place. Up to JDK 5.0, this class used to create class describtor only for the java.io.Serializable or java.io.Externalizable using lookup() API. In JDK 6.0, this class usage extended to offer for non-serializable classes using lookupAny(Class<?> cl)




import java.io.ObjectStreamClass;
import java.io.Serializable;

public class ObjectStreamClassTest {

public static class EmployeeBean implements Serializable {
String name;
String designation;
}

/**
* @param args
*/
public static void main(String[] args) throws Exception {
Class<EmployeeBean> employeeBean = (Class<EmployeeBean>) Class
.forName("ObjectStreamClassTest$EmployeeBean");

ObjectStreamClass oscT = ObjectStreamClass.lookup(employeeBean);
System.out.println("Old look up not gets for ObjectStreamClass: "
+ oscT);

oscT = ObjectStreamClass.lookupAny(employeeBean);
System.out.println("lookupAny gets for ObjectStreamClass: "
+ oscT.getSerialVersionUID());
System.out.println(oscT.getField("name"));

EmployeeBean emp = (EmployeeBean)oscT.forClass().newInstance();
System.out.println("Name :"+ emp.name + " Desig: " + emp.designation);

}
}


Output could like below:
Old look up not gets for ObjectStreamClass: ObjectStreamClassTest$EmployeeBean: static final long serialVersionUID = 7687813253144298513L;
lookupAny gets for ObjectStreamClass: 7687813253144298513
Ljava/lang/String; name
Name :null Desig: null



Remove implementing Serializable in EmployeeBean and run this program. We will see the inconsistent in serialVersionUID, fields. However, we could able to create instance of JAVA object using ObjectStreamClass class.



Note:
Compile and run the above code using the compiler source and target in JDK 6.0 version.

Sunday, December 20, 2009

Externalizable

java.io.Externalizable



Externalizable interface extends java.io.Serializable, whereas this interface comes with two methods to store and retrieve data from Object Stream and this is not marker interface. This approach gives luxury of deciding to application developer, what to be serilized and what not to be. However, this technique enforces that the order in it stored in stream, the same order, has to be used to read back.




import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ExternalizableTest {

public static class EmployeeBean implements Externalizable {

private static final long serialVersionUID = 4258520358186173223L;

String name;

String designation;

public String getName() {
return name;
}

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

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
// TODO Auto-generated method stub

name= (String)in.readObject();
designation=(String)in.readObject();

}

public void writeExternal(ObjectOutput out) throws IOException {
// TODO Auto-generated method stub
out.writeObject(name);
out.writeObject(designation);
}
}
public static void main(String[] args) throws Exception {

ExternalizableTest.EmployeeBean emp = new EmployeeBean();

emp.setName("Krishna");

FileOutputStream bos = new FileOutputStream(new File("/tmp/a.txt"));
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(emp);
out.close();

FileInputStream bis = new FileInputStream(new File("/tmp/a.txt"));
ObjectInputStream in = new ObjectInputStream(bis);
EmployeeBean empFromPersist = (EmployeeBean) in.readObject();
System.out.println("Employee name from persisted Bean ::" + empFromPersist.getName());
in.close();
}

}



The above code will stores and retrieves two fields.



If number of read operations is not equivalent in readExternal to write operations in writeExternal then following Exception



Exception in thread "main" java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1349)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at ExternalizableTest$EmployeeBean.readExternal(ExternalizableTest.java:42)
at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1792)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at ExternalizableTest.main(ExternalizableTest.java:65)

Serializable

java.io.Serializable



java.lang.Serializable interface is markable interface, which intimates to JVM and ObjectStreamClass that this class possible to persist. All the fields in this class will be persisted while writing into stream using ObjectOutputStream class. Persisted data will be restored using ObjectInputStream



Persisting object is useful in following cases

  • to transmit object state over network

  • to transmit object state to other JVM

  • store and recreate object from the particular state of object




In the folloing program, EmployeeBean object is stored in file '/tmp/a.txt', and using this persistance, EmployeeBean object is recreated and name field value also get restored from file.




import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStreamClassTest {

public static class EmployeeBean implements Serializable {
String name;

String designation;

public String getName() {
return name;
}

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

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}
}

public static void main(String[] args) throws Exception {

ObjectStreamClassTest.EmployeeBean emp = new EmployeeBean();
emp.setName("Krishna");

FileOutputStream bos = new FileOutputStream(new File("/tmp/Employee.txt"));
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(emp);
out.close();

FileInputStream bis = new FileInputStream(new File("/tmp/Employee.txt"));
ObjectInputStream in = new ObjectInputStream(bis);
EmployeeBean empFromPersist = (EmployeeBean) in.readObject();
System.out.println("Employee name from persisted Bean ::" + empFromPersist.getName());
in.close();

}
}


serialVersionUID


Unique Identifier used to identify the version of the class, which helps to identify the class in which object stream is generated and also instructs JVM to restore Object using the class which has same version UID. The serialVersionUID is computed using the signature of a stream of bytes that reflect the class definition.



serialver tool comes with JSDK, which helps to generate UID.

use: serialver [-classpath classpath] [-show] [classname...]



Serializable implementing class has to have a serialVersionUID field. If this field is not declared explicitly, then JVM will create serialVersionUID in runtime and assign for a class. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values. serialVersionUID generation costly for JVM in runtime, and more over, unexpected serialVersionUID may get created.



If serialversionID mismatched, we do get following exception

Exception in thread "main" java.io.InvalidClassException: ObjectStreamClassTest$EmployeeBean; 
local class incompatible: stream classdesc serialVersionUID = 4258520358186173223, local class serialVersionUID = 0
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:562)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1583)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)




If Streamed class not found in, target system where strea get read, then ClassNotFoundException will be thrown.


import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class ObjectStreamClassTest {

public static void main(String[] args) throws Exception {

FileInputStream bis = new FileInputStream(new File("/tmp/Employee.txt"));
ObjectInputStream in = new ObjectInputStream(bis);
EmployeeBean empFromPersist = (EmployeeBean) in.readObject();
System.out.println("Employee name from persisted Bean ::" + empFromPersist.getName());
in.close();
}
}

If we run above code after '/tmp/Employee.txt' creation using the above sample code. Following exception will be thrown



Exception in thread "main" java.lang.ClassNotFoundException: ObjectStreamClassTest$EmployeeBean
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:604)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1575)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at ObjectStreamClassTest.main(ObjectStreamClassTest.java:47)



Content in Object Stream



What will be stored in Employee.txt?

Content will be organized as documented in Object Serialization Specification, Section 2, Object Output Classes


  1. The class name.
  2. The class modifiers written as a 32-bit integer.
  3. The name of each interface sorted by name.
  4. For each field of the class sorted by field name (except private
    static
    and private transient fields:

    1. The name of the field.
    2. The modifiers of the field written as a 32-bit integer.
    3. The descriptor of the field.

  5. If a class initializer exists, write out the following:

    1. The name of the method, <clinit>.
    2. The modifier of the method, java.lang.reflect.Modifier.STATIC,
      written as a 32-bit integer.
    3. The descriptor of the method, ()V.

  6. For each non-private constructor sorted by method name and signature:

    1. The name of the method, <init>.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method.

  7. For each non-private method sorted by method name and signature:

    1. The name of the method.
    2. The modifiers of the method written as a 32-bit integer.
    3. The descriptor of the method.

  8. The SHA-1 algorithm is executed on the stream of bytes produced by DataOutputStream and produces five 32-bit values sha[0..4].
  9. The hash value is assembled from the first and second 32-bit values of the SHA-1 message digest.
    If the result of the message digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named sha, the hash value would be computed as follows:

    long hash = ((sha[0] >>> 24) & 0xFF) |
    ((sha[0] >>> 16) & 0xFF) << 8 |
    ((sha[0] >>> 8) & 0xFF) << 16 |
    ((sha[0] >>> 0) & 0xFF) << 24 |
    ((sha[1] >>> 24) & 0xFF) << 32 |
    ((sha[1] >>> 16) & 0xFF) << 40 |
    ((sha[1] >>> 8) & 0xFF) << 48 |
    ((sha[1] >>> 0) & 0xFF) << 56;






Serializable : Class Hierarchical



If Class implements Serializable then its subclass also serializable. In the below code, if we write EmployeeBean object and retrieve field values for EmployeeBean.


public Organization implements Serializable {
String orgname; ...
}

public class EmployeeBean extends Organization {...}



Though superclass did not implement Serializable, subclass implements Serializable then only the subclass fields are serialized. In the below sample, orgname field will not be serialized.


public Organization {
String orgname; ...
}

public class EmployeeBean extends Organization implements Serializable{... }



Flexibility


While restoring Object state from Stream, following things will not harm restore operation




  1. Class may have +/- in number of methods.

  2. Class may have +/- in number of fields.

  3. Access modifier may get changed for fields and methods.

  4. Order of fields will not be counted.

  5. Implementing interface and superclass also be not counted.

  6. and etc.,



Transient keyword


Some of the Java classes not possible to persist and reuse in target environment. For instance, java.io.File created in machine A and refering path some xYZ, whereas there is no guarantee, that same path is exist in target machine B. In general, java.io packaged classes will not serialized.



In some cases, business mandates that certain fields need not to be serialzed, which has to be prevented in serialization operation. To do this, we have to define the variable with transient keyword.



Field value will not be restored if target machine declares the variable with transient, though Source machine declares particular variable as non-transient variable.


transient String name;

MySQL: Backup and Restore

Backup and Restore MySQL Database


This tutorial explains the how to backup and restore the MySQL Database. Databases are used to store large amount of precious data and it becomes very important to Backup your data. In case case of some hardware or software failures backup data can be used to restore the Database.


Backing Up MySQL Database
MySQL database backup can be accomplished in two ways:
a) Copying the raw mysql database files &
b) Exporting tables to text files


Copying the MySQL database files
MySQL uses the same table format on different platforms, so it's possible to copy MySQL table and index files from one platform and use them on another without any difficulties (assuming, of course, that you're using the same version of MySQL on both platforms).


Exporting tables to text files
The MySQLDump is handy utility that can be used to quickly backup the MySQL Database to the text files. To use the MySQLDump utility it is required to logon to the System running the MySQL Databse. You can use Telnet to remotely logon to the system if you don't have the physical access to the machine.


The syntax for the command is as follows.
mysqldump -u [Username] -p [password] [databasename] > [backupfile.sql]
[username] - this is your database username
[password]- this is the password for your database
[databasename] - the name of your database
[backupfile.sql] - the filename for your database backup

Let's discuss the example of backing up MySQL Database named "accounts" into text file accounts.sql. Here are the scenarios of taking the backup assuming that both user name and password of the database is "admin".


a) Taking the full backup of all the tables including the data.
Use the following command to accomplish this:
mysqldump -u admin -p admin accounts > accounts.sql


b) Taking the backup of table structures only.
Use the following command to accomplish this:
mysqldump -u admin -p admin --no-data accounts > accounts.sql


c) Taking the backup data only.
Use the following command to accomplish this:
mysqldump -u admin -p admin --no-create-info accounts > accounts.sql


Restoring MySQL Database
Restoring the MySQL is very easy job. You can use the following to command to restore the accounts database from accounts.sql backup file.


mysql - u admin -p admin accounts


In this tutorial you learned how to take the backup of your MySQL Database and restore the same in the event of some database crash or on some other machine.

Wednesday, December 16, 2009

NoClassDefFoundError

java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError



java.lang.ClassNotFoundException vs java.lang.NoClassDefFoundError



JAVA throws for fatal issues Error and recoverable issues as Exception. While it comes to class loading exception/error, it is really a myth for developer, who are novice to classloader and its behaviour. Aforementioned classes get used to intimate the issue based on the nature of the class loading.



In general, these issues raises for the same reason of non-existing class in run time. The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found in the time of Application getting executed.




ClassLoader



ClassLoader used to load the bytecodes and convert the same to runnable format based on the platform. In classLoader, findClass() and loadClass() are the methods which helps us to create the instance of objects. loadClass() method get called by JVM, to load class, where new class reference found in the application. If already the definition of class found then Class object will be returned. If given class reference not loaded already then findClass() get called and implementation of this method responsible to find the binary for the class. Once binary found then findClass() method which calls defineClass() to return Class object.



ClassNotFoundException



This class extends Exception. After throwing this exception also ClassLoader can able to proceed and will not break the application.

Thrown when an application tries to load in a class through its string name using:


  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader. This is final method and get called by JVM..
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found. Default implementation of findClass() also throws ClassNotFoundException.



The above mentioned APIs are pretty safe and mostly used to make lazy loading of classes. Even specified class not found also, no issues application implementor can decide to take alternate approach of business.



For instance, We have Web container application, and ClassLoader is written by us to load classes(eg: Servlet) which are comes part of web application. While doing web application deployment, our ClassLoader has to load the classes referred in web.xml as Servlet. If any one of the class not found then it has to throw just an exception, and rollback deployment. No need of webcontainer stop, it can continue to doing its business.



ClassNotFoundException.java
public class ClassNotFoundExceptionTest {
public static void main(String[] args) {
Class.forName(""); // empty space also throws ClassNotFoundException
ClassLoader.getSystemClassLoader().loadClass("NonExistingClass$subclass"); // non-existing class in classpath
}}


$javac *.java

$java ClassNotFoundExceptionTest
Exception in thread "main" java.lang.ClassNotFoundException:
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:4)


Comment Class.forName(""); line and compile and run

Exception in thread "main" java.lang.ClassNotFoundException: NonExistingClass$subclass
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at ClassNotFoundExceptionTest.main(ClassNotFoundExceptionTest.java:5)





NoClassDefFoundError



This error occurs whenever JVM could not able to progress application due to non-existing class reference found in object creation.



Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.




Create following classes in a same folder and compile both java files.

MainClass.java
public class MainClass {
public static void main(String[] args) {
Object a= new NonExistingClass();
}
}
NonExistingClass.java
public class NonExistingClass {}



$javac *.java

$java MainClass
No error will be thrown

$ rm NonExistingClass.class

$ java MainClass
Exception in thread "main" java.lang.NoClassDefFoundError: MainClass
Caused by: java.lang.ClassNotFoundException: MainClass
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: MainClass. Program will exit.



Evenmore, we can see NoClassDefFoundError in JVM startup, by refering non-existing class
$ java NonExistingClass
Exception in thread "main" java.lang.NoClassDefFoundError: NonExistingClass
Caused by: java.lang.ClassNotFoundException: NonExistingClass
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Could not find the main class: NonExistingClass. Program will exit.

Best practice: ReentrantReadWriteLock

Best practice: ReentrantReadWriteLock

Excellent lock and unlock mechanism to make thread safe particular code using ReentrantReadWriteLock. For instance, specified thread made lock and due to some exception, thread did not reach to unlock code and came out of run() method. We may think that presence of Thread does not exist now, the lock whatever acquired by the thread has to be release after a while. Reality is not that, no way we can get/reclaim the lock in ReentrantReadWriteLock. It would be nice to have such an API to fire and release weakReferenced Threads lock and facilitate the Reader/Writer to acquire the lock.



In JDK1.6, It is our code job to release the lock whenever it compeleted or else some exception happened while doing process.



Best practice to keep unlock code always in finally block, to make sure all locks release before coming out of the thread. If you run, following code, this program will not be terminated and T2 wait for ever.




import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantTest {
private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(true);
private static  ReentrantReadWriteLock.ReadLock readlock=rwl.readLock();
private static  ReentrantReadWriteLock.WriteLock writelock=rwl.writeLock();

public static void main(String[] args) throws Exception{

new Thread()
{
@Override
public void run() {
System.out.println("entering into lock for T1");
readlock.lock();
System.out.println("Lock Acquire for T1");
//readlock.unlock();
}
}.start();

new Thread()
{
@Override
public void run() {
try{sleep(100);}catch(Exception e){}
System.out.println("entering into lock for T2");

writelock.lock();

System.out.println("Lock Acquire for T1");
}
}.start();

// Thread.sleep(10000);
}
}



Best practice would be, place unlock as used below


writelock.lock();
try
{
//business goes here
}finally
{
writelock.unlock();
}

readlock.lock();
try {
//do read operation here
} finally {
readlock.unlock();
}

Tuesday, December 15, 2009

java.util.concurrent.Semaphore

java.util.concurrent.Semaphore

If we wants to make programmatically Connection management, connection may be Database or TCP Socket or JMS or other. Instead of establishing connection every time for every SQL command, we can cache the connection for future use. Once the usage of connection usage is completed then we can take connection back to pool. For instance, We have established 20 connections, but 50 SQL commands has to be run in the given point of time. These 20 connections has to be alotted to first 20 SQL commands to run and whenever SQL command is completed then connection will be used for rest of SQL commands.



We have to maintain a mark for each connection that whether that connection is get used or not. Two methods has to be used to acquire and release the resource. Everything perfect, who will take care of filtering and ordering the thread entry, how thread state managed. For these questions Semaphore is the right answer, here is the code snippet




class ConnectionPool {
private static final int MAX_AVAILABLE = 100;
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

public Object getConnection() throws InterruptedException {
available.acquire();
return getNextAvailableItem();
}

public void releaseConnection(Object x) {
if (markAsUnused(x))
available.release();
}

protected Object[] connections = ... whatever kinds of connections being managed
protected boolean[] used = new boolean[MAX_AVAILABLE];

protected synchronized Object getNextAvailableItem() {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (!used[i]) {
used[i] = true;
return connections[i];
}
}
return null; // not reached
}

protected synchronized boolean markAsUnused(Object item) {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (item == connections[i]) {
if (used[i]) {
used[i] = false;
return true;
} else
return false;
}
}
return false;
}

}

java.util.concurrent.ExecutorCompletionService

java.util.concurrent.ExecutorCompletionService

In the given scenario, if we wants to run FIVE events and do some specific operation after every event compeletion. If this is fixed number of events it is very easy to fall in CountDownLatch otherwise we have to go with ExecutorCompletionService .



More than that we can use our own ExecutorService to build the ExecutorCompletionService and also cabable of running Callable and Runnable and returns the result. If it is Runnable, whatever the value we passed for the result will be returned after Thread completion.



submit(...)
This method helps to add Runnable and Callable
take()
Removes first Runnable and Callable from the completion Queue, if no thread completed it waits for completion
poll()
Removes first Runnable and Callable from the completion Queue, if no thread completed, returns null



CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e);
ecs.submit(t1);
ecs.submit(t2);
.....

ecs.take(); //wait for atleast one thread to complete
while(ecs.poll() != null);  //continue this loop to complete second thread in queue.

java.util.concurrent.CyclicBarrier JSR166

java.util.concurrent.CyclicBarrier

Assume the scenario, I have to transfer money from my bank account to my friend account. In the first phase, my account details and balance is verified and validate. Now, amount has to be debited in my account and creadited in my friend account. While commiting the changes in these two transaction, if any exception comes then these two activity has to be get informed. credit/debit operations are happening in multithreaded environment, How to achive this scenario. In older ages, we have to reiniate two more threads to rollback these operation.



CyclicBarrier helps us to achive this and intimate back to the threads who are all waiting for the commit operation, to take necessary action using the exception BrokenBarrierException. The CyclicBarrier uses an all-or-none breakage model for failed synchronization attempts. Common operation which needs to run at the end of multiple threads operation, will go in Runnable implementation.



We do not wants to do any special operation as common for all the threads, however we wants to end all the thread in same time. For example, first thread may take 5minutes to complete the operation, whereas second thread may take 1Hour to complete. Assume T2 has to complete prior to T1 thread completion, then CyclicBarrier has to instantiate without Runnable object.



import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
final CyclicBarrier cb = new CyclicBarrier(2, new Runnable() 
{
public void run() {
System.out.println("Commit Operation - Completed");
}
});

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T1 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T1 post-commit");
}
}.start();

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T2 pre-commit");
try
{
cb.await();
}catch (Exception e)
{
//do something commit operation failed
}
System.out.println("T2 post-commit");
}
}.start();
}
}

java.util.concurrent.CountDownLatch JSR166

java.util.concurrent.CountDownLatch

Assume, in multi-threaded environment, we have an usecase where TWO operations has to be completed before we start the business. How do I monitor these TWO operations result and start the 3rd operation. If any fixed number of operation needs to be done before starting the business then CountDownLatch is the right choice.



We have to create instance of CountDownLatch with an integer, where integer specifies that number of operation has to be done.



CountDownLatch cdl = new CountDownLatch(2);


Where countdownlatch created for 2 activities. Either this 2 activity may be done in a single thread or in multiple threads.

countDown()
Each time this method called from CountDownLatch, subtracts 1 from count. It goes upto ZERO.
await()
This method blocks currentThread until CountDownLatch value comes to ZERO and returns true. if timeout specified in await(long timeout, TimeUnit unit) and If the specified waiting time elapses then the value false is returned.
getCount()
Gives how many operations yet to go. We can eventually use CountDownLatch count to display progressbar also.




import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {

public static void main(String[] args) {

final CountDownLatch cdl = new CountDownLatch(2);

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T1 complete");
cdl.countDown();
}
}.start();

new Thread() {
@Override
public void run() {
try{sleep(1000);}catch(Exception e){}
System.out.println("T2 complete");
cdl.countDown();
}
}.start();

try {
System.out.println("MainThread waits for T1 and T2 thread to complete");
cdl.await();
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("All threads are completed");
}
}

Monday, December 14, 2009

Thread : Wait and Notify

Thread : Wait and Notify



We use sleep() method in Thread to pass the thread for some milliseconds/nanoseconds and resume the thread on its own. However, while waiting for the shared resource, this will not help.

In JAVA, Object class comes with wait() and notify/notifyAll methods, which helps us to mark saying, I am waiting for this object, who ever owns object monitor lock, release and let me know. While calling this methods, we have to own the object monitor lock of this





public class WaitNotifytest {
static Object obj=new Object();

public static void main(String[] args) throws Exception{
new Thread()
{
@Override
public void run() {
try
{
obj.wait();
}catch(Exception e)
{
e.printStackTrace();
}
}
}.start();

new Thread()
{
@Override
public void run() {
obj.notify();
}
}.start();

Thread.sleep(1000);
}
}




If the above program will throw java.lang.IllegalMonitorStateException

java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:485)
at WaitNotifytest$1.run(WaitNotifytest.java:21)
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at WaitNotifytest$2.run(WaitNotifytest.java:59)




notify and wait with Object monitor lock



notify() method awakes only one thread in the queue(no gaurantee in order), rest has to wait for awakened thread to notify().





public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T1");
obj.notify();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T2");
obj.notify();
}

} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
obj.notify();
}

}
}.start();
}
}



notifyAll


Each thread notifies after usage of object. If T1 and T2, wants to make read access of object then T3 alone notfiy to all the threads. To do this notifyAll() method get used. This method should only be called by a thread that is the owner of this object's monitor, otherwise we will get the IllegalMonitorStateException. Awakened Threads will compete each other runs/access this object.




public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T1");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait();
System.out.println("T2");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
obj.notifyAll();
}
}
}.start();
}
}


In this program only one notifyAll method called on object to release all the lock.

Note:

  • If wait() called on the object and no notify signal received then this wait called thread will wait for ever. However, there could be a chance of thread awaking without any of notificatin like notify, timeout or interrupt. This is called spurious wakeup. This will happen in rare condition.


  • We can even specify the time, how long maximum this thread to wait to acquire the lock, even if other thread is not signalled notify/notifyAll, however object lock is released and no other thread acquires lock of this object.



wait with max timeout




public class WaitNotifytest {
static Object obj = new Object();

public static void main(String[] args) throws Exception {

new Thread() {
@Override
public void run() {
try {
synchronized (obj) {
obj.wait(400);
System.out.println("T1");
// obj.notify();

}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();

new Thread() {
@Override
public void run() {
synchronized (obj) {
try{Thread.sleep(10000);}catch(Exception e){}
// obj.notifyAll();

}
}
}.start();
}
}

Thread: Join API

Thread: Join API

In multithreaded environment, T2 thread may need the result from T1 thread. Hence, T2 needs to check the thread state of T1 until the T1 state turn to TERMINATED in specified polling interval using sleep API.





while(Thread.State.TERMINATED != t1.getState())
{
Thread.sleep(1000);//wait for 1 second
}



This loop takes considerable CPU time. Instead of we do this thread monitoring job in our code base to wait for the particular thread's completion. We can utilize the Thread API join(), which minimize the CPU cycle usage and avails as similar functionality.



threadObj.join() API makes current Thread to wait for threadObj to complete.


public class JoinTest {
public static void main(String[] args) {
final Thread t1= new Thread()
{
@Override
public void run() {
for(int i=0;i<1000;i++)
{
System.out.println(i);
}
}
};

Thread t2= new Thread()
{
@Override
public void run() {

// Using sleep and state check in our code
// while(Thread.State.TERMINATED != t1.getState())
// {
// try{Thread.sleep(1000);//wait for 1 second
//
// }catch(Exception e)
// {
// e.printStackTrace();
// }
// }

//Using join API
try{t1.join();}catch(Exception e)
{
e.printStackTrace();
}

System.out.println("Hello From T2, after T1 terminated");
}
};

t2.start();
t1.start();


}
}

java.util.ConcurrentModificationException and ConcurrentHashMap

ConcurrentModificationException comes whenever modification happened in the time of iteration operation happening in the Collections objects like HashMap, AbstractList and etc.,

Eventually within the iterator loop, if we try to add item to Map also we get this exception.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;


public class concurrentMaptest {

public static void main(String[] args) throws Exception{
final Map<Integer,Integer> m= new HashMap<Integer, Integer>();
for(int i=0;i<1000;i++)
{
m.put(i, i);
}

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
Entry<nteger,Integer> ent=it.next();

m.put(ent.getKey()+1, ent.getValue());
}
}
}.start();

new Thread()
{
@Override
public void run() {
Iterator<Entry<nteger,Integer>> it=m.entrySet().iterator();
while(it.hasNext())
{
it.next();
it.remove();
}
}
}.start();

Thread.sleep(1000);

System.out.println(m);
}
}



Following exception trace will be the outcome of this program

Exception in thread "Thread-0" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at java.util.HashMap$EntryIterator.next(Unknown Source)
at concurrentMaptest$1.run(concurrentMaptest.java:24)


java.util.concurrent.ConcurrentHashMap



java.util.concurrent.ConcurrentHashMap is an utility class which follows complete spec of HashMap( except null key is not allowed) and makes lock-free threadsafe collection operations.


For instance, change the HashMap declaration line as below and run the program, we won't face any Exception

final Map<Integer,Integer> m= new ConcurrentHashMap<Integer, Integer>(); 



Sunday, December 13, 2009

Executors and Implementations JSR 166

Executors and Implementations JSR 166

We do face OutOfMemory error not only because of Heap size, eventually because of number of threads get created in JVM. Managing threads lifecycle will cost lot than actual business implementation. JSR 166 comes with interfaces Executor, ExecutorService, and ScheduledExecutorService.

ScheduledExecutorService subinterface of ExecutorService and ExecutorService is subinterface of Executor.

Executor has execute(Runnable command) API.

Prior to JSR166, we create a new thread and set the context and/or classloader bringing the thread to runnable state will take considerable time. Similarly, garbage collector has to clear the dead thread references.

In JSR166, Executor takes and treats all new thread(Thread object, Runnable implementation object) as a job and the same will get run and produce result with using available or predefined worker threads.

java.util.concurrent.Executors class has n number of factory methods which helps to create the thread pools based on our need.


  • newFixedThreadPool(...) fixed number of threads will be created and used to run all the job

  • newSingleThreadExecutor() only one thread will do job one by one

  • newCachedThreadPool() Integer.MAX_VALUE threads possible to create automatically and reuse based on the jobs load. Once job is done then thread may die if no more jobs found in queue

  • newSingleThreadScheduledExecutor() schedule the job time to run in a single thread

  • newScheduledThreadPool(int corePoolSize) schedule the job time to run, based on corePoolSize threads will be created and reused

  • unconfigurableExecutorService(ExecutorService) this ExecutorService freeze thread pool configuration and allows to executes job based on ExecutorService delegated in this.




ThreadPoolExecutor



Above mentioned ExecutorService are not enough for the realtime business. For instance, my application wants to establish 300 HTTP connection at a time, means that 300 runnable has to run in a given time, there could be more than 300 jobs may wait in queue. Instance of java.util.concurrent.ThreadPoolExecutor class will help us to do this

new ThreadPoolExecutor(300, Integer.MAX_VALUE,60L, TimeUnit.SECONDS, new SynchronousQueue());

where 1st argument is corePoolSize, 2nd maxPoolSize, 3rd keepAlive, 4th Queue object

Based on Queueing mechanism, Executor behaves differently

  • Direct handoffs(eg: SynchronousQueue) - if no thread available to run new task then fails. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection.

  • Unbounded queues (eg: LinkedBlockingQueue)- no use of specifying maxPoolSize, upto maximum of corePoolSize threads will be created and kept for keepalive time if no new job found. No rejection possible until Integer.MAX_VALUE reached. But, keep in mind if this grows, we get OutOfMemory error for Heapspace.

  • Bounded queues (eg: ArrayBlockingQueue) - Rejection possible if it tasks count in queue increase more than maxPoolSize



ThreadFactory



In general, threads will be created with normal priority and with default context. Or else, we may need to do some manipulation in the time of thread creation as a pre-thread creation activity, then ThreadFactory interface helps to do that.


class myThreadFactory implements ThreadFactory
{
Thread newThread(Runnable r)
{
System.out.println("new thread is created");
Thread t =new Thread(r);
t.setPriority(Thread.MAX_PRIORITY); // maximum priority set to threads created for this pool
}

}



Callable and Future interfaces



I have submitted job and I would like to check the status of the task and also wants to get the result from the task completion. To achieve this, instead of Runnable interface implementation, we have to implement Callable implementation which has a method call(...) with return type.


FutureTask<String> future =
new FutureTask<String>(new Callable<String>() {
public String call() {
return "your job result goes here";
}});
executor.execute(future);

or else


Future<String> future = executor.submit(new Callable<String>() {
public String call() {
return searcher.search(target);
}});
executor.submit(future);



future.get() returns the result of task once it get completed.

Assume I need to cancel, after enqueued job in future queue, then FutureTask class will be useful.

Package java.util.concurrent.atomic : JSR 166

Package java.util.concurrent.atomic : JSR 166

Primitive Types



This package helps to write lock free and threadsafe programming. Currently, this packages designed to operate on primitive types int and long. Since int is supported, boolean primitive type also be supported.

java.util.concurrent.atomic.AtomicInteger
java.util.concurrent.atomic.AtomicLong
java.util.concurrent.atomic.AtomicBoolean


For instance, I do need to

class Incrementtwo {
private Atomicinteger intNumber = new AtomicInteger(0);
public long next() {
intNumber.getAndIncrement(); //equivalent to i++;
intNumber.incrementAndGet(); //equivalent to ++i;
return intNumber.intValue(); // get int value without any +/- operations
}
}



Similarly, we do have following APIs for AtomicLong and AtomicInteger,

  • to decrement - getAndDecrement() , decrementAndGet()

  • adding/substracting value from delta using APIs - addAndGet(int delta), getAndAdd(int delta)
      if delta is negative then this will do subtraction, there is no separate API for subtraction

  • Plain set APIs - addAndGet(int delta), getAndSet(int newValue)

  • converting to otherprimitive type's value- longValue(),floatValue(), doubleValue(),intValue()

  • Only set value if expected value present- compareAndSet(int expect, int update) , weakCompareAndSet(int expect, int update)
    • weakCompareAndSet performance wise good and possible to face spurious error,
    • this API makes difference with compareAndSet only for Refernces,Updadater.




AtomicBoolean has only set APIs.

Definitely, these APIs are not an alternate for wrapper classes(Integer, Long), since wrapper classes are immutable and has its own hashcode and the equals() logic. Howeever, these Atomic classes are mutable and operates on hashCode and equals of Class.


Array



We have seen how to get, set and increment and decrement values for Integer and Long, how to do it for Arrays of Integer and Long. AtomicIntegerArray AtomicLongArray.

All the above listed APIs available for atomic array class, and almost all the api holds first argument as index of the array.

Reflection



Everything is perfect, I have already a class which cannot be modified by me, because of the fact that comes from our dependency product. How to make sure atomiccally update and get volatile variables. Yes, AtomicIntegerFieldUpdater, and AtomicLongFieldUpdater supports. For instance,



import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

public class AtomicIntTest {
static class bean
{
volatile int i=0;
}
public static void main(String[] args) {
AtomicIntegerFieldUpdater fu= AtomicIntegerFieldUpdater.newUpdater(bean.class, "i");
bean obj=new bean();
System.out.println(fu.get(obj));
System.out.println(fu.incrementAndGet(obj));
System.out.println(fu.get(obj));
}


Reflection approach may give performance challenges.


Object References:
Is Atomic only support Integer,Long and Boolean ? , No. We can ahieve atomic for float and double by convertint into integer and long using the APIs(floatToIntBits, doubleToLongBits). Eventually, there is a way to deal with object references.

For example, I have send a object reference to an API, where I have to set the different reference to given object reference. In JAVA, we can not change object variable reference until unless the change directly apply to that object variable address. To resolve this issue, we have classes AtomicReference, AtomicReferenceArray, and AtomicReferenceFieldUpdater.

Reference atomicity support extended to intimate that whether this object still alive by marking bit(AtomicMarkableReference) and to hold the version based access to the references by stamping with integer value with reference pair.


import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicIntTest {
static class bean
{
volatile int i=0;


}
public static void main(String[] args) {

int[] iarray={0,1,2};
bean obj=new bean();
bean obj1=new bean();
bean obj2=new bean();
AtomicStampedReference asr=new AtomicStampedReference(obj,0);
obj1.i=1;

asr.set(obj1,1);
System.out.println(asr.getReference().i); //print i value as 1
asr.set(obj2,2);

System.out.println(asr.get(iarray).i); //print i value as 0

obj2.i=2;
asr.weakCompareAndSet(obj1, obj2, 1, 0);
System.out.println(asr.getReference().i); //print i value as 2

System.out.print(asr.get(iarray).i); //print i value as 2

}
}

Thursday, December 10, 2009

Volatile keyword

Volatile

Synchronized block accepts only objects, how do I synchronize primitive data types. We can not go with Wrapper classes like Integer, Double, since these classes are the immutable. Each new value assigned to variable of these wrapper class objects, creates new objects.

Generally, each thread will take it own copy of the value and operates and stores back to the original address of the variable (means, caching the value in thread and stores back to the actual location). Run the following code, in very rare condition, we will see duplicate numbers and/or maximum number will be less than 100. If this issue araised in customer place, then we may go mad and talk to manager saying that it is not possible to reproduce in our environment. In lighter side, you may get travel to customer place or relatively pink notice ;)


import java.util.ArrayList;
import java.util.List;

public class VolatileIncrement {
int x = 0;
public void f() { x++; }
public String toString() { return Integer.toString(x); }
public static void main(String[] args) {
final VolatileIncrement vi = new VolatileIncrement();
List<Thread> threads=new ArrayList<Thread>();
for(int i=0;i<100;i++)
{
Thread t1 = new Thread() {
@Override
public void run() {
vi.f();
System.out.println(vi);
}
};

threads.add(t1);
}
for(Thread t:threads)
{
t.start();
}

}
}

volatile is the keyword which tells to threads that MUST operate with the actual address, instead of caching. We are get gauranteed to get always solid result in multithreaded environment for the primitive data types.

volatile int x=0;


what could be the differences of volatile and synchronized keywords

volatile - operates on primitive data type, no thread safe possible for block of code or method
synchronized - operates on block of code or method, thread safe for block code and its objects

Wednesday, December 9, 2009

Concurrencey Utility: ReentrantReadWriteLock JSR 166

Concurrencey Utility: ReentrantReadWriteLock

1.5 onwards - package java.util.concurrent.locks

We have seen how to use synchronize keyword in method and in block of code. It is painstaking work that synchronizing the access of class level APIs and the object level using synchronize keyword. No guarantee of acquiring the lock in the order of thread arrived for wait queue.

JSR 166, comes with an approach which is similar to the synchronized mutual exclusive way of locking particular object. However, instead of acquiring the lock for the object (which will not allowed to access simultaneously), lock and granting work is given to the thirdparty. Means that which thread has to be allowed to access particular block of code, based on the operations(read/write).

ReentrantReadWriteLock RWL=new ReentrantReadWriteLock();
RWL.readLock().lock();
//do read operation -
RWL.readLock().unlock();

RWL.writeLock().lock();
//do write operation
RWL.writeLock().unlock();


Reentrant

Is this enough if we get guarantee in order of thread arrives to acquire the lock. Definitely not, we have to prioritize threads based on the business.

For instance, 100 different threads trying to access the block of code to make read only operation on the data, and waiting for the lock, now a thread comes with write operation. Will this thread will be waited long for other 100 threads to complete. No, write lock will highest priority of acquiring the lock and all other 100 threads(read lock) has to await to completion of last write lock.

Fairness

Not yet, ordering of read lock is guaranteed among the threads which are awaiting for read lock. How to order this sequence ?
Fairness option is introduced in concurrency utility, if we really interested in order, we have to pass 'true' as a value for fairness.

ReentrantReadWriteLock RWL=new ReentrantReadWriteLock(true);

Downgrading

If fair value set to true then performance will be degraded considerablly. How to tackle this issue, either minimizing the lock required block of code or downgrading the write lock based on need basis. For instance, Write lock acquiered for 10 lines of code, where as , write operation completes in 5th line, if we keep write lock upto 10th line then other writers also needs to wait, or if no write waiting for acquiring the lock then readers also needs to be waited. In 6th(after writeoperation) line of code, read lock acquired and write lock realeased then other writers can start doing the operation. This is called Downgrading. Keep in mind in this block of code , 9th line has read operation which possibly run after all the writer threads completed :(.

Note:
Can i acquire write lock within reader block ?
No, Within the writer block, we can acquire read lock, not vice-versa.

Why do i need to use read lock ?
Obsolutely, no need of read lock if your business logic not mandates to get very latest updated value. As I mentioned above, 100 readers has to wait for 1 wirter thread. If we are not introducing this reader lock then there could be possibility that 100 readers may get different values based on the order it get executes.

In my business 500 reader and rarely writer will occur, will reader lock cause any performance issue?
Not exactly, if no writer thread found in the given point of time then reader will not be blocked. Means, multiple reader(reader threads) can read at the same time. Read lock is used for getting writer threads changes immediate affect in all other reader threads.

Tuesday, December 8, 2009

Synchronized

Java: Synchronized

Every JAVA developer may be heard on and off about this word from JDK 1.0 . And, still there are lots of JAVA developers go with the myth.

JAVA is multithreaded language, where any block of code or any method can be run simultaneously by different Thread(s).

Synchronized keyword used in method signature to specify that this method can be run single thread at a time.

Is this enough to filter that all the thread in accessing particular method. No, we have to obtain lock for the particular resource, then only we can really implement filtering/preventing

simultaneous access.

Object lock : If synchronized keyword used in non-static methods in a class, then the object created from this class lets threads to access this method one by one on this object. For

instance, two object created from this class then T1 access obj1.getMethod() and T2 access obj2.getMethod(), this will run parallelly, since these two are different objects.

Class level Lock: If synchronized keyword used in stato method in a class then class level lock will be obtained. At a single point in time , only one static method can be accessed.

If I have a class with one static and another non-static method with synchronized keyword, then these two methods possibly run in parallel.

Above defined synchronized keyword helps in usecase of preventing simultaneous access of instance/class level variables. In real time, we are not required to block all the variable

access, and which will lead to get performance bottleneck. To avoid this mutex approach has to be used, means, that only the lockable object has to be locked instead of the whole

object and class level lock. For this synchronized block has used.

synchronized(this){
//do single threaded activity
}


The above code does the job equivalent to synchronized keyword in methods. However, this will perform better than the synchronized keyword, since the call waits after the context

switching of the method, but earlier method entry itself limited and filtered.


In the below code, static and non-statice present with synchronized keyword, and both method shares the same variable ind and almost all the time ind value as 20 in last line of

output. However, there could be possibility of getting some other number due to ind variable is not a volatile. I will explain in forthcoming blogs about volatile keyword.

public class Sync {
static int ind = 0;
public synchronized void wow() {
for (int i = 1; i <= 10; i++) {
System.out.println("hello " + ++ind);
try {
Thread.sleep(5);
} catch (Exception e) {
}
System.out.println("kris " + ind);
}

}

public static void wow1() {
for (int i = 1; i <= 10; i++) {
System.out.println("wow " + ++ind);
try {
Thread.sleep(5);
} catch (Exception e) {
}
System.out.println("d " + ind);
}
}

public static void main(String[] args) {
final Sync s = new Sync();
Thread t1 = new Thread() {
@Override
public void run()
wow1();
}
};

Thread t2 = new Thread() {
@Override
public void run() {
s.wow();
}
};

t1.start();
t2.start();

}
}



Additionally, If you want to test only object lock then in replace run method of T2 in T1.


Note:
1. synchronized keyword will not be used in constructor, since object creation will not be ever thread safe in JAVA.
2. Assume that 100 threads are trying to access the same synchronized block/method, no guarantee in order to get lock to run.
3. By calling wait() method, currently object lock holding thread can release the resource. Same thread will be try to acquire the lock if notify() or notifyAll() method in the same object

get called by the other RUNNING thread, which holds lock. No gurantee in order of which thread calls wait(), to obtain lock again.

java.util.concurrent package has the implementation to guarantee the order of the thread waits in obtaining lock for read and write.

@See java.util.concurrent.locks.ReentrantReadWriteLock

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com