Posts

Showing posts from October, 2015

null values in concurrent HashMap, HashMap, HashTable - Java

The main reason that nulls aren't allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can't be accommodated. The main one is that if  map.get(key)  returns  null , you can't detect whether the key explicitly maps to  null  vs the key isn't mapped. In a non-concurrent map, you can check this via  map.contains(key) , but in a concurrent one, the map might have changed between calls.

Weak Reference, Strong Reference - Java

Java provides two different types/classes of  Reference Objects :  strong  and  weak ; then, weak Reference Objects can be further divided into  soft  and  phantom . Let's go per point. Strong Reference Object StringBuilder builder = new StringBuilder (); It's the default type/class of Reference Object, if not differently specified:  builder  is a strong Reference Object. This kind of reference makes the referenced object not eligible for GC, this means: whenever an object is referenced by a  chain of strong Reference Objects , it cannot be garbage collected. Weak Reference Object WaekReference < StringBuilder > weakBuilder = new WeakReference < StringBuilder >( builder ); It is not the default type/class of Reference Object, in order to be used it should be explicitely specified like in the above example. This kind of reference makes the references object eligible for GC, this means: in case the only refere...

WeakHashMap - Java

WeakHashMap  is an implementation of  Map  interface where the memory of the value object can be reclaimed by Garbage Collector if the corresponding key is no longer referred by any section of program. This is different from HashMap where the value object remain in  HashMap  even if key is no longer referred. We need to explicitly call remove() method on HashMap object to remove the value so that it can be ready to be reclaimed(Provided no other section of program refers to that value object). Calling remove() is an extra overhead. Here is a simple program which demonstrate the difference:- import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; public class WeakMap { public static void main(String[] args) { Map weak = new WeakHashMap(); Map map = new HashMap(); { String weakkey = new String("weakkey"); weak.put(weakkey,new Object()); String key = new String("key"); map.put(key, new Object()); weakkey = ...

JVM hashcode function - Java

It depends on which VM you are using. Assuming that you are using Oracle default JVM - which is HotSpot, then I can tell you that HotSpot has six  hashCode()  implementations. You can choose it using  -XX:hashCode=n  flag running JVM via command line, where n: 0 – Park - Miller RNG ( default ) 1 – f ( address , global_statement ) 2 – constant 1 3 – Serial counter 4 – Object address 5 – Thread - local Xorshift

PowerMock vs Mockito - Java

Features given by adding PowerMock on top of the Mockito : mock static, final and private methods remove static initializers allow mocking without dependency injection

Static Serialization - Java

Statics are implicitly transient, so you don't need to declare them as such. Serialization is for serializing  instances , not  classes . Static fields (methods are irrelevant since they are part of the class definition so they aren't serialized) will be reinitialized to whatever value they are set to when the class is loaded. If you have a mutable static field, then the changes made to that value will be lost.

LRU Implementation - Java

import java.util.LinkedHashMap ; import java.util.Map ; /** * Created by skupunarapu on 10/19/2015. */ public class LRUImpl extends LinkedHashMap<Integer , String> { private static final long serialVersionUID = 1L ;   private int capacity ; public LRUImpl( int capacity , float loadFactor){ super (capacity , loadFactor , true ) ;   this . capacity = capacity ; } @Override protected boolean removeEldestEntry (Map.Entry<Integer , String> eldest) { return size() > this . capacity ; } public static void main (String arg[]){ LRUImpl lruCache = new LRUImpl( 4 , 0.75f ) ; lruCache.put( 1 , "Object1" ) ; lruCache.put( 2 , "Object2" ) ; lruCache.put( 3 , "Object3" ) ; lruCache.get( 1 ) ; lruCache.put( 4 , "Object4" ) ; System. out .println(lruCache) ; lruCache.put( 5 , "Object5" ) ; ...

JSP implicit objects - Java

JSP supports nine Implicit Objects which are listed below: Object Description request This is the  HttpServletRequest  object associated with the request. response This is the  HttpServletResponse  object associated with the response to the client. out This is the  PrintWriter  object used to send output to the client. session This is the  HttpSession  object associated with the request. application This is the  ServletContext  object associated with application context. config This is the  ServletConfig  object associated with the page. pageContext This encapsulates use of server-specific features like higher performance  JspWriters . page This is simply a synonym for  this , and is used to call the methods defined by the translated servlet class. Exception The  Exception  object allows the exception data to be accessed by designated JSP.

Java pass by value - Java

Java is always  pass-by-value . Unfortunately, they decided to call pointers references, thus confusing newbies. Because those  references  are passed by value. It goes like this: public static void main ( String [] args ){ Dog aDog = new Dog ( "Max" ); foo ( aDog ); if ( aDog . getName (). equals ( "Max" )) { //true System . out . println ( "Java passes by value." ); } else if ( aDog . getName (). equals ( "Fifi" )) { System . out . println ( "Java passes by reference." ); } } public static void foo ( Dog d ) { d . getName (). equals ( "Max" ); // true d = new Dog ( "Fifi" ); d . getName (). equals ( "Fifi" ); // true } In this example  aDog.getName()  will still return  "Max" . The value  aDog  within  main  is not overwritten in the function  foo  with the  Dog   "Fifi"  as the object r...

Address n nodes data structure - Java

package com.ds.trees ; import java.util.ArrayList ; import java.util.List ; /** * Created by skupunarapu on 10/16/2015. */ public class Address { public static void main (String[] args) { AddrNode addrNodeCountry = new AddrNode() ; addrNodeCountry.setValue( "India" ) ; addrNodeCountry.setAncestor( null ) ; AddrNode addrNodeSAP = new AddrNode() ; addrNodeSAP.setValue( "Andhra Pradesh" ) ; addrNodeSAP.setAncestor(addrNodeCountry) ; AddrNode addrNodeSTel = new AddrNode() ; addrNodeSTel.setValue( "Telangana" ) ; addrNodeSTel.setAncestor(addrNodeCountry) ; AddrNode addrNodeSTN = new AddrNode() ; addrNodeSTN.setValue( "Tamil Nadu" ) ; addrNodeSTN.setAncestor(addrNodeCountry) ; AddrNode addrNodeDHyd = new AddrNode() ; addrNodeDHyd.setValue( "Hyderabad" ) ; addrNodeDHyd.setAncestor(addrNodeSTel) ; addrNod...

Serializable vs Externalization - Java

1. In case of Serializable,  default serialization process  is used. while in case of Externalizable custom Serialization process is used which   is implemented by application. 2. JVM gives call back to  readExternel()  and  writeExternal()  of  java.io.Externalizalbe  interface for restoring and writing objects into persistence. 3.  Externalizable  interface provides complete control of serialization process to application. 4.  readExternal()  and  writeExternal()  supersede any specific implementation of  writeObject  and  readObject  methods. T hough Externalizable provides complete control, it also presents challenges to serialize super type state and take care of default values in   case of  transient variable  and  static variables in Java . If used correctly  Externalizable  interface can improve performance of serialization process. Read...

Palindrome of a number - Java

public class Reverse { public static void main (String[] args) { int revNum = reverse ( 12345 ) ; System. out .println(revNum) ; } public static int reverse ( int num) { int revNum = 0 ; while (num != 0 ){ int rem = num % 10 ; revNum = revNum * 10 + rem ; num = num / 10 ; } return revNum ; } } public class Palindrome { public static boolean isPalindrome ( int number){ if (number == Reverse. reverse (number)) return true; else return false; } public static void main (String[] args) { System. out .println( isPalindrome ( 12321 )) ; } }

Session Factory scope - Hibernate - Java

Session factory objects are to be implemented using the  singleton  design pattern. Instances of SessionFactory are  thread-safe  and typically shared throughout an application. As these objects are heavy weight because they contains the connection information, hibernate configuration information and mapping files,location path. So creating number of instances will make our application  heavy weight . But the session objects are not thread safe. So in short it is - SessionFactory objects are one per application and Session objects are one per client. Hence it would be one SessionFactory per DataSource. Your application may have more than one DataSource so you may have more than one SessionFactory in that instance. But you would not want to create a SessionFactory more than once in an application. Advantages : Obviously its improving performance of your application :) UPDATE - Extract from  Hibernate Doc The internal state of a SessionFactory is i...

Servlet Concurrency - Java

Image
A Java servlet container / web server is typically multithreaded. That means, that multiple requests to the same servlet may be executed at the same time. Therefore, you need to take concurrency into consideration when you implement your servlet. To make sure that a servlet is thread safe, there are a few basic rules of thumb you must follow: Your servlet service() method should not access any member variables, unless these member variables are thread safe themselves. Your servlet service() should not reassign member variables, as this may affect other threads executing inside the service() method. If you really, really need to reassign a member variable, make sure this is done inside a synchronized block. Rule 1 and 2 also counts for static variables. Local variables are always thread safe. Keep in mind though, that the object a local variable points to, may not be so. If the object was instantiated inside the method, and never escapes, there will be no problem. On the othe...

What is a web service - Java

A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.

Scope of a Spring-Controller and its instance-variables - Spring - Java

yes, Spring MVC controllers are singletons by default. An object field will be shared and visible for all requests and all sessions forever. However without any synchronization you might run into all sorts of concurrency issues (race conditions, visibility). Thus your field should have  volatile  (and  private , by the way) modifier to avoid visibility issues. Back to your main question: in Spring you can use  request-  (see  4.5.4.2 Request scope ) and session-scoped  (see:  4.5.4.3 Session scope ) beans. You can inject them to controllers and any other beans (even singletons!), but Spring makes sure each request/session has an independent instance. Only thing to remember when injecting request- and session-scoped beans into singletons is to wrap them in scoped proxy (example taken from  4.5.4.5 Scoped beans as dependencies ): <!-- an HTTP Session-scoped bean exposed as a proxy --> <bean id = "userPreferences" class = "c...

interface vs abstract - Java

Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. A Java class can implement multiple interfaces but it can extend only one abstract class. public interface LoginAuth { public String encryptPassword ( String pass ); public void checkDBforUser (); } Now suppose you have 3 databases in your applicatio...