Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, 18 January 2015

Java Memory Model

  1. Each thread running in the Java virtual machine has its own thread stack.
  2. The thread stack also contains all local variables for each method being executed (all methods on the call stack). A thread can only access it's own thread stack. Local variables created by a thread are invisible to all other threads than the thread who created it. Even if two threads are executing the exact same code, the two threads will still create the local variables of that code in each their own thread stack.
  3. The heap contains all objects created in your Java application, regardless of what thread created the object.
  4. An object may contain methods and these methods may contain local variables. These local variables are also stored on the thread stack, even if the object the method belongs to is stored on the heap.
  5. As already mentioned, the Java memory model and the hardware memory architecture are different. The hardware memory architecture does not distinguish between thread stacks and heap. On the hardware, both the thread stack and the heap are located in main memory. Parts of the thread stacks and heap may sometimes be present in CPU caches and in internal CPU registers.
  6. The volatile keyword can make sure that a given variable is read directly from main memory, and always written back to main memory when updated.
  7. With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads data from main memory into CPU caches, or writes data from CPU caches to main memory.
  8. A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance.
  9. A thread that calls wait() on any object becomes inactive until another thread calls notify() on that object. In order to call either wait() or notify the calling thread must first obtain the lock on that object. In other words, the calling thread must call wait() or notify() from inside a synchronized block.
  10. Once a thread calls wait() it releases the lock it holds on the monitor object. This allows other threads to call wait() or notify() too, since these methods must be called from inside a synchronized block.
  11.   
  12. The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

     
  13.  As I have mentioned earlier, if two threads are both reading and writing to a shared variable, then using the volatilekeyword for that is not enough. You need to use synchronization in that case to guarantee that the reading and writing of the variable is atomic.
    But in case one thread reads and writes the value of a volatile variable, and other threads only read the variable, then the reading threads are guaranteed to see the latest value written to the volatile variable. Without making the variable volatile, this would not be guaranteed.


       

Friday, 19 December 2014

Parsing XML files in JAVA

  1. Use the SAX parser for large files http://stackoverflow.com/questions/15132390/parsing-large-xml-documents-in-java
  2. http://elegantcode.com/2010/08/07/dont-parse-that-xml/
  3. The DOM Parser loads the complete XML content into a Tree structure. And we iterate through the Node and NodeList to get the content of the XML
  4. SAX Parser is different from the DOM Parser where SAX parser doesn’t load the complete XML into the memory, instead it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser.
  5. StAX stands for Streaming API for XML and StAX Parser is different from DOM in the same way SAX Parser is. StAX parser is also in a subtle way different from SAX parser.
    The SAX Parser pushes the data but StAX parser pulls the required data from the XML.
    The StAX parser maintains a cursor at the current position in the document allows to extract the content available at the cursor whereas SAX parser issues events as and when certain data is encountered.
XMLInputFactory and XMLStreamReader are the two class which can be used to load an XML file. And as we read through the XML file using XMLStreamReader, events are generated in the form of integer values and these are then compared with the constants inXMLStreamConstants.
  1.  

Garbage Collection in Java

Thursday, 18 December 2014

Design Pattern CheatSheet

Observer Pattern : The observer pattern defines a one to many relationship between objects so that when one object changes state all the other dependent objects are notified.

Factory Pattern : encapsulates object creatio. Defines an interface for creating an object, but lets subclass decide which class to instantiate. Factory method lets a class defer instantiation to subclasses. 

Adapter Pattern : Converts interfaces of a class to another interface that clients expect. Lets classes work together that wouldnt otherwise because of incompatible interfaces.

Singleton - Use double check locking because the synchronization is only needed for the object instantiation part. If you already have an instance of that object, you dont need to do the synchronization. Declare the instance as static volatile, the constructor as private and a getInstance function as public static. 

Command Pattern : encapsulates a request as an object , thereby letting you parameterize other objects with different requests, queue or log requests and support undoable operations. Light will have OnCommand and OffCommand and it will be there in the remote control. You can queue such incoming commands.Command pattern gives you a way to package a piece of computation or actions and the receiver and store it as a first class object.

Decorator Pattern : Doesnt alter the interface, but add responsibility to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. In the decorator design pattern the class or abstract class that is being extended is also present as a property in the class extending it.

Facade : Make interface simpler. The facade pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

Strategy Pattern : Encapsulate interchangeable behavior and use delegation to decide which behavior to use. 

Template Method : Defines the skeleton of an algorithm in a method in an abstract class, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

A hook is a method that is defined in an abstract class, but only given an empty or default implementation. This gives the subclass the ability to hook into the algorithm at various points, if they wish, a subclass is also free to ignore the hook.

Iterator Pattern : The iterator pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation

Observer Pattern - The observer interface is implemented by all observers. The update method has paramters which are received by all observers when the state of the subject changes.
WeatherData implements the Subject interface which registersObservers, UpdatesObservers, RemovesObservers. It also holds a list of observers.
The ConcreteObserver stores a reference to the subject where it registers. This is not necessarily needed. This functionality is given so that the observer can unregister from the subject if it feels like.

We say that a module has high cohesion when it is designed around a set of related functions and say it has low cohesion when it is designed around a set of unrelated functions. Classes that adhere to a single responsibility principle have high cohesion. Every responsibility of a class is an area of change. More than one responsibility means more than one area of change. 

OO Principles :
  1. Encapsulate what varies (encapsulating object creation is factory, encapsulating method invocation is , encapsulating algorithms is template pattern, encapsulate iteration over different data types is iteration, )
  2. Favor composition over inheritance
  3. Program to interfaces not implementations
  4. Strive for loosely coupled designed between objects that interact
  5. Classes should be open for extension but closed for modification
  6. Depend on abstractions and do not depend on concretions
  7. Only talk to friends (Facade pattern and principle of least knowledge)
  8. Dont call us, we will call you (Hollywood principle, Template)

Principles :
  1. Dependency Inversion : Avoid the use of concrete classes and instead work with as much abstractions as possible.
  2. Principle of least knowledge : Objects should talk to only few friends. The principle prevents our system such that we have large number of classes coupled together so that changes to one part of the system cascade to other parts. When you build a lot of dependencies between many classes you build a fragile system that will be costly to maintain and difficult for others to understand. 
  3. Hollywood Principle : Dependency rots happen when you have high level components depending on low level components depending on high level components depending on sideways components depending on low level components and so on. We allow low level components to hook themselves into a system, but the high level components determine when they are needed and how. In other words, the high level components give the low level components a "Dont call us, we will call you.".
  4. Open Principle : Classes should be open for extension but closed for modification - decorator pattern

Wednesday, 17 December 2014

Tuesday, 12 August 2014

What is the web.xml file used for ?

Generally speaking, this is the configuration file of web applications in java. It instructs the servlet container (tomcat for ex.) which classes to load, what parameters to set in the context, and how to intercept requests coming from browsers.
There you specify:
  • what servlets (and filters) you want to use and what URLs you want to map them to
  • listeners - classes that are notified when some events happen (context starts, session created, etc)
  • configuration parameters (context-params)
  • error pages, welcome files
  • security constriants
In servlet 3.0 many of the web.xml parts are optional. These configurations can be done via annotations (@WebServlet@WebListener)

Monday, 28 July 2014

Too many open files error java mac

-XX:- MaxFDLimit

Directs the VM to refrain from setting the file descriptor limit to the default maximum. The default behavior is to set the limit to the value specified by OPEN_MAX, which is10240. Normally, this is the maximum number of files that a process may have open. It is possible, however, to increase this limit to a user-specified value with the sysctlutility. Under such circumstances, you may want to pass -XX:-MaxFDLimit to stop the Java VM from restricting the number of open files to 10240.