<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7450758598965295876</id><updated>2024-12-18T19:22:41.566-08:00</updated><title type='text'>TecHceT Crazzy</title><subtitle type='html'>Right place for techies feast</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><link rel='next' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default?start-index=26&amp;max-results=25&amp;redirect=false'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>108</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-8836859341422785393</id><published>2012-10-20T23:14:00.000-07:00</published><updated>2012-10-20T23:14:12.738-07:00</updated><title type='text'>Design Patterns</title><content type='html'>Design Patterns


Design Patterns are basically a catalog of common interactions between objects. These interactions have been found, tested/tried, and optimized by skilled programmers to help others in solving some of their very common programming problems in an efficient way. Design Patterns simply illustrate how objects can communicate with each other without being much concerned about their individual data models and methods. This clear separation helps building robust and scalable design solutions to various programming problems. If you&#39;ve already made this separation in your code (which is highly possible in Object Oriented Dev) then you&#39;re already using some of the widely used Design Patterns.


There are various formal definitions of Design Patterns and almost all of them convey the same message. Find below one such popular definition given by Gamma, et al., 1993.


“Patterns identify and specify abstractions that are above the level of single classes and instances, or of components.”


What are Communication Patterns?


Design Patterns do discuss design of objects as well, but what makes them even more important is that they describe an elegant and efficient methods of communication between the involved objects and this is the reason why Design Patterns are also referred to as Communication Patterns.


How many Design Patterns are currently available?


There is no fixed answer to this question. The original Design Patterns book included 23 design patterns and these are the most widely used patterns having several known applications using them. But, we currently have hundreds of Design Patterns documented/presented in some form or the other and many of them have already gained a good popularity. There are few which are suitable only for some very specific problems and hence not so popular. These Design Patterns are applicable at many levels ranging from very low level specific problems to general system-wide problems. Understanding of these Design Patterns may become extremely beneficial in designing solutions as they have been found/tested/tried by experts and it&#39;s highly unlikely that most of us will come up with a better design on the fly.


Types of Design Patterns


The authors of the original Design Pattern book deivided the 23 patterns into three categories based on what actually the patterns do in a design solution. These categories are:-

    Creational - the design patterns belonging to these category are used for creating objects. Using such a design pattern provides more flexibility where we require a control over the creation of objects. One very common use case is the usage of a creational design pattern to restrict the total number of instances of a class. Example: The Singleton Pattern, The Abstract Factory Method Pattern, etc. Read more - Creational Design Patterns &amp; their Examples &gt;&gt;
    Structural - as the name suggests this category groups all those design patterns which help the user to group objects into larger structures to meet the complex requirements in a structured way. A common use case is to use such a design pattern for designing a complex user interface. Example: The Adapter Pattern, The Proxy Pattern, etc. Read more - Structural Design Patterns &amp; their Examples &gt;&gt;
    Behavioral - the patterns belonging to this category are used to define communication between objects of a proposed solution. In other words such design patterns helps defining the flow of a complex system. Example: The Chain of Responsibility Pattern, The Strategy Pattern, The Iterator Pattern, etc.


What do Design Patterns suggest for Object Oriented programming?


The goal of Design Patterns (as discussed in the first section of the article) is to maintain a clear separation between classes so that they need to know (and hence depend) very little on each other. Object Oriented Programming has two popular mechanisms of enforcing separation which are: Inheritance and Encapsulation. Based on these two separation mechanisms Design Patterns suggest two important precepts which are:-


Programs should be based on Interface and NOT on implementation - If you&#39;re using inheritance then you may have unnecessary access to other methods/members of the base class and you may keep carrying all that extra load throughout the inheritance chain and this may subsequently cause many undesirable issues especially when the inheritance chain the underlying system becomes large and complex. You can avoid such a potential issue by having an abstract class at the top of the hierarchy and having the specific implementation in the corresponding sub classes only.


Composition should be preferred over Inheritance - does it seem contrary to the customs of Object Oriented Programming Methodology? Well... it isn&#39;t actually. Interitance may cause some undesirable side-effects in certain cases whereas Composition is usually (or probably always) pretty safe to use without worrying about any possible side-effects even when the classes evolve to newer versions which may not be the same in case of Inheritance.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/8836859341422785393/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/design-patterns.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/8836859341422785393'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/8836859341422785393'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/design-patterns.html' title='Design Patterns'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-9080931453502721419</id><published>2012-10-20T23:13:00.003-07:00</published><updated>2012-10-20T23:13:15.532-07:00</updated><title type='text'>Differences between Swing and AWT. When to use what?</title><content type='html'>Differences between Swing and AWT. When to use what?


&quot;Swing&quot; was actually the code name used by Sun during the development and it was planned that on release the extension will be known as JFC (Java Foundation Classes), but Swing managed to beat JFC in popularity even after the release of the package.


Swing package can be used with Java 1.1 as well. For that we need to include three JARs - swing.jar, swingall.jar, windows.jar in the CLASSPATH and the packages are named &#39;com.sun.java.swing.*&#39;, &#39;com.sun.java.swing.event.*&#39;, etc. In Java 1.2 the package names changed to &#39;javax.swing.*&#39;, &#39;javax.swing.event.*&#39;, etc. as the concept of extensions were introduced in Java 1.2 (Java 2 Platform).


Main Differences between Swing and AWT


Swing comonents are light-weight as compared to AWT components for the simple reason that they don&#39;t make use of the native UI components of the underlying platform.


Swing components haven been written completely in Java language. Not the same with AWT as it uses native libraries.


Swing components use relatively less number of classes as compared to AWT components not only because the it doesn&#39;t depend on native code, but also because it has a better design due to its evolution from AWT. Most of the design flaws got fixed which ultimately led to lesser redundancies.


The look and feel of the Swing components is defined only by the Swing extension classes and it&#39;s pluggable to have the look and feel of the underlying platform as well whereas the look and feel of the AWT comonents is mostly goverened by the underlying platform. By default, Swing components open up in their own look and feel.


Swing extension is completely based on the MVC (Model View Controller) architecture and hence the inherent benefits of the MVC design pattern add more value to the usage of Swing.


In addition there are few other trivial differences as well. For example: Swing extension has a richer set of components as compared to AWT, Swing&#39;s JPanel automatically gets double buffered and gets repainted faster, etc.


When to use what?


Due to all these advantages, Swing has almost entirely relaced AWT and you got to have a really strong reason if you are still using AWT in your application which is very hard to find at least for platform-independent applications.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/9080931453502721419/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/differences-between-swing-and-awt-when.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/9080931453502721419'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/9080931453502721419'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/differences-between-swing-and-awt-when.html' title='Differences between Swing and AWT. When to use what?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-5683312595602375304</id><published>2012-10-20T23:12:00.003-07:00</published><updated>2012-10-20T23:12:41.399-07:00</updated><title type='text'>How to create zip/jar files programmatically in Java</title><content type='html'>How to create zip/jar files programmatically in Java

Write a Java application which automatically zips the directories. The application should accept the input and output directories specified either through command prompt or via a properties file. The user should be able to specify From Date and To Date if s/he wishes so that only those directories in the specified input directory which have their last modified date in that range get zipped.


public class CreateZip{

private static FileOutputStream fos = null;
private static ZipOutputStream zos = null;
private static int BUFFER = 2048;
private static String inputDir = &quot;C:\\input&quot;;
private static String outputDir = &quot;C:\\output&quot;;
private static Date fromDate = null;
private static Date toDate = null;
private static boolean ZIP_ALL = false;

public CreateZip(){
}

public static void checkDirectories(){

File inputDirectory = new File(getInputDir());
File[] dirList = null;

if(inputDirectory.exist())
if(inputDirectory.isDirectory()){
dirList = inputDirectory.listFiles();
int len = dirList.length;

for(int i = 0; i&lt; dir =&quot; dirList[i];&quot; lastmodified =&quot; dir.lastModified();&quot;&gt; fromDate.getTime()
 || lastModified == fromDate.getTime())
 &amp;&amp; (lastModified &lt; lastmodified =&quot;=&quot; filelist =&quot; dir.listFiles();&quot; nooffiles =&quot; fileList.length;&quot; nooffiles =&quot;=&quot; zipfilename =&quot; getOutputDir()&quot; fos =&quot; new&quot; zos =&quot; new&quot; i =&quot; 0;&quot; fis =&quot; new&quot; bis =&quot; new&quot; zipentry =&quot; new&quot; data =&quot; new&quot; bytecount =&quot; bis.read(data,&quot;&gt; -1){
 zos.write(data, 0, byteCount);
}
System.out.println(filePath + &quot; added&quot;);
} catch(Exception e){
System.out.println(&quot;Exception thrown while reading the file: &quot; + e);
System.exit(1);
}
}

public static void main(String[] args){
if(args.length == 0)
setZIP_ALL(true);
else if(args.length == 2){
setInputDir(args[0]);
setOutputDir(args[1]);
}
else if(args.length == 4){
setInputDir(args[0]);
setOutputDir(args[1]);

//... using deprecated method just for testing
setFromDate(new Date(args[2]);
setToDate(new Date(args[3]);
}
else{
System.out.println(&quot;Incorrect Usage!&quot;);
System.exit(1);
}

System.out.println(&quot;Starting the zipping process...&quot;);
CreateZip.checkDirectories();
System.out.println(&quot;Completed the zipping process!&quot;);
}

//... getters and setters of the fields
...




This draft version of the application is just to give you an idea of how easily can you write a Java application to automate the zipping process.

Similarly, you can create JAR file automatically using an almost identical Java program. You just need to change &#39;ZipOutputStream&#39; with &#39;JarOutputStream&#39;, &#39;ZipEntry&#39; with &#39;JarEntry&#39; and probably you&#39;re done! Just try out in case you find it interesting.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/5683312595602375304/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-create-zipjar-files.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5683312595602375304'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5683312595602375304'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-create-zipjar-files.html' title='How to create zip/jar files programmatically in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-4609685051132503375</id><published>2012-10-20T23:11:00.005-07:00</published><updated>2012-10-20T23:11:49.040-07:00</updated><title type='text'>Session implementation of a Web App spread on multiple JVMs/Servers</title><content type='html'>Session implementation of a Web App spread on multiple JVMs/Servers

Should you need a refreshed understanding of what HTTP Sessions are and why are they actually needed, please refer to the article - Need for Session Tracking and Session Tracking Mechanism &gt;&gt;

All the three techniques of HTTP session maintenance namely Cookies, URL Rewriting, and Hidden Fields have quite a few limitations. Some of them are:

    Support for small volume of data - especially in case of URL Rewriting as can be easily understood.
    Support for simple character data only - URLs are made up of character strings.
    Vulnerable to attacks - since all the data is visible to the clients hence attackers may get hold of the data and change them in between before the request reaches the server.
    Developer needs to manage the session - the entire responsibility of maintaining the session (when to use the existing and when to create a new, ensuring uniqueness, consistent client-session integration, etc.) comes to the developer which obviously adds to the complexity of the overall application development.


How can we manage the session more effectively and more easily?

Using the HttpSession interface of the The Java Servlet Specification is one of the possible ways of maintaining the sessions more effectively and far more easily. All the J2EE compliant containers have the implementation of the underlying classes and the user simply need to call the APIs to use the services. For example, calling getSession() will return the session for the corresponding client if it already exists otherwise it will create a new session. Similarly, we can use the APIs putAttribute(String attrName, Object attrValue) and getAttribute(String attrName) to save the attribute values to the session OR to get them from the session, respectively. Here the important point to note is that we can save a value of type Object (i.e., effectively any Data Type supported by Java) which means we are no more limited to the character based name-value pairs. Almost all of the above mentioned limitations either get eliminated OR at least get reduced to a considerable extent by using this approach. Right?

Managing the Session Manager of your Application Server

Almost all the Application Servers come with an integrated Session Manager which facilitates an even easier way of configuring the session handling for your web application by facilitating the session configuration via simple GUI screens. You may refer to your Web/App Server manual for more details. Some common taks which we can do via App Server Session Manager are:

    Enable Sessions - if it&#39;s not enabled then the runtime system will throw an exception if the servlet tries to create one (and of course no existing session would be returned as there wouln&#39;t be any existing...right?). Why at all do we need this configuration? Well... because not all your web applications require Session Support and for them it&#39;s wiser to disable this feature to avoid the extra overhead which the runtime system incurs for session management.
    Enable Cookies - Ohh, back to Cookies again? Yeah... the reason why we still need cookies is because we need the client to maintain the unique Session ID of the session object created and maintained on the server. But, now we are left with storing just a single ID either in the Cookies or via URL Rewriting and not the entire session information. That definitely makes a web developer&#39;s life easier.
    Enable URL Rewriting - Again for the same purpose of passing the unique Session ID to and from the individual clients. This of course requires a piece of code to be written as the Session ID needs to be added to the URL programmatically and hence this approach is not supported for static pages (plain HTML pages). How to overcome this limitation? Pretty simple... convert all the plain HTML pages to JSP pages as every HTML page is a valid JSP page so this should not be a problem. You would of course not like to convert your static HTML pages to Servlets :-) You of course need to encode the URL in these converted JSP pages as well. Any JSP page or Servlet which doesn&#39;t do the URL encoding will not be able to access the session if it relies on URL Rewriting approach. Beware of this!
    Enable Persistent Sessions - sessions are maintained in the Application/Web Server memory and hence the data will be lost if the server is shut down. If you&#39;re interested in maintaining the session data then you need to store it in some database or in some other persistent medium. Almost all the Application Servers support this feature and you just need to specify the Data Source which would be used to store the session data.


What will happen if both &#39;Enable Cookies&#39; and Enable URL Rewriting&#39; are enabled?

If both these features are selected then the approach which would actually be used to maintain the session will depend upon the browser setting (to see if it accepts cookies or not) and also on the fact whether Servlet (in use) is using URL encoding or not. Below are the two possible cases where the session will be maintained if both &#39;Enable Cookies&#39; and &#39;Enable URL Rewriting&#39; are enabled:

    Servlet has URL Encoding code - if this is the case then URL Rewriting approach will be used irrespective of whether Cookies are enabled or not. Even if the browser is set to accept the Cookies.
    No URL Encoding code in Servlet and Browser accepting Cookies - cookies approach will be followed to maintain the sessions.


Implementing HTTP sessions for Web Applications spread across multiple physical servers (or JVMs)

Say your Web Application is spread across multiple physical servers (or may be on the same server, but using different JVMs which is of course a rarity) which might have been done to balance the load of your application OR may be the requirement is such that separate physical servers is a need than a luxury. Whatever be the case, in such a scenario if a user say log into one of the machines (JVMs to be specific) and then s/he is taken to some other Servlet/JSP running on some other server (JVM) to fulfill the client request. Now if that Servlet/JSP also requires authentication (which it would in most of the practical scenarios) then the user would be prompted to enter his/her credentials once again which s/he would of course not like. It&#39;s the applications responsibility to transfer the credentials from one server (JVM) to another)... right?

Using Persistent Sessions, we can easily achieve a solution to this complex problem. This approach requires the session to be saved in a data source which can easily be accessed by any of the scattered servers (JVMs) and the client gets a feeling that his application is virtually running on a single server (JVM). It&#39;s a better practice to have a completely separate data Source just for the purpose of session persistence and not to integrate session data with the application data source(s) for the obvious reason of making the overall implementation loosely coupled and hence better maintainable and more scalable.

Though the Session Manager discussed above behaves more or less the same for all the popular Application Servers like BEA WebLogic, IBM WebSphere, Oracle Application Server, etc., but the article is based on IBM WebSphere Application Server.

References: Maintaining Session Data with WebSphere, The WebSphere InfoCenter</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/4609685051132503375/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/session-implementation-of-web-app.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/4609685051132503375'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/4609685051132503375'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/session-implementation-of-web-app.html' title='Session implementation of a Web App spread on multiple JVMs/Servers'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-206208321077633400</id><published>2012-10-20T23:11:00.002-07:00</published><updated>2012-10-20T23:11:14.886-07:00</updated><title type='text'>2&#39;s Complement: Binary representation of negative numbers in Java</title><content type='html'>2&#39;s Complement: Binary representation of negative numbers in Java

Negative numbers in Java are represented using 2&#39;s complement. As we know that integers in Java occupy 4 bytes so to understand how a negative integer (say -4) is represented internally in Java, we first need to find the binary equivalent of the positive value of the integer (in this case 4) and subsequently by finding the 2&#39;s complement of that binary representation.

Okay, so how do find 2&#39;s complement of a binary number? Simply by adding &#39;1&#39; to the 1&#39;s complement of that number. But, how to find 1&#39;s complement of a binary number then? Just by reverting the bits of the number i.e., changing 1s to 0s and 0s to 1s. An example may of of some help here.

...
int i = -4;
...

Step #1: Binary Equivalent of the positive value (4 in this case)

0000 0000 0000 0000 0000 0000 0000 0100

Step #2: 1&#39;s complement of the binary rep of 4 by inverting the bits

1111 1111 1111 1111 1111 1111 1111 1011

Step #3: Finding 2&#39;s complement by adding 1 to the corresponding 1&#39;s complement

1111 1111 1111 1111 1111 1111 1111 1011
0000 0000 0000 0000 0000 0000 0000 0001
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1100

Thus, we see that integer -4 is represented by the binary sequence (1111 1111 1111 1111 1111 1111 1111 1100) in Java.

Once we have an understanding of how the numbers are represented internally, bit-level manipulation becomes easily understandable, which otherwise is obviously one of the hardest things in Java (or any other language supporting that) to visualize.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/206208321077633400/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/2s-complement-binary-representation-of.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/206208321077633400'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/206208321077633400'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/2s-complement-binary-representation-of.html' title='2&#39;s Complement: Binary representation of negative numbers in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-2052497357079907134</id><published>2012-10-20T23:10:00.003-07:00</published><updated>2012-10-20T23:10:43.068-07:00</updated><title type='text'>How to find whether a number is a power of 2 or not in Java?</title><content type='html'>How to find whether a number is a power of 2 or not in Java?

There can be many possible solutions to this problem, but probably the most efficient remains to be the one which uses bit-level manipulation wisely.

We&#39;ll talk about only that solution here and since it involves bit-level manipulation of binary sequences, so should you require a refresh, first go through this article - 2&#39;s complement, 1&#39;s complement, representation of negative numbers in Java &gt;&gt;

As is the case with many other solutions which use bits intelligently, this one is also very compact. That&#39;s the beauty of bit-handling. Let&#39;s first see what the solution is and then try to understand it. It becomes very easy to understand once you get the binary sequence representations right.

Java method to check if the passed parameter is a power of 2 or not


public boolean checkIfItsPowerOf2(int n){

 if( (n &amp; -n) == n){
  
  //passed parameter is a power of 2
  return true;
 }
 else{
  //not a power of 2
  return false;
 }
}



Illustration: We&#39;ll see the working of the method for a few sample numbers , say &#39;1&#39;, &#39;2&#39;, and &#39;3&#39; to understand it completely.

1: Binary representation of 1

0000 0000 0000 0000 0000 0000 0000 0001

-1: Computation of binary representation of -1 by finding 2&#39;s complement of 1

1111 1111 1111 1111 1111 1111 1111 1110 (1&#39;s complement of &#39;1&#39;)
0000 0000 0000 0000 0000 0000 0000 0001 (adding 1)
---------------------------------------
1111 1111 1111 1111 1111 1111 1111 1111 (-1 = 2&#39;s complement of 1)

1 &amp; -1: applying bit-wise AND (&amp;) operator on 1 and -1

0000 0000 0000 0000 0000 0000 0000 0001
1111 1111 1111 1111 1111 1111 1111 1111
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 0001 (1 &amp; -1)

Thus we see that the test ((1 &amp; -1) == 1) will return &#39;true&#39;. This is correct as 1 is a power of 2 (1 = 2^0).

2 &amp; -2: applying bit-wise AND on 2 and -2

0000 0000 0000 0000 0000 0000 0000 0010 (binary rep of 2)
1111 1111 1111 1111 1111 1111 1111 1110 (-2 = 2&#39;s comp of 2)
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 0010 (2 &amp; -2)

i.e., ((2 &amp; -2) == 2) will return &#39;true&#39; and that&#39;s correct as 2 is again a power of 2 (2 = 2^1)

3 &amp; -3: applying bit-wise AND on 3 and -3

0000 0000 0000 0000 0000 0000 0000 0011 (binary rep of 3)
1111 1111 1111 1111 1111 1111 1111 1101 (-3 = 2&#39;s comp of 3)
---------------------------------------
0000 0000 0000 0000 0000 0000 0000 0001 (3 &amp; -3)

i.e., ((3 &amp; -3) == 3) will return &#39;false&#39; which is correct as 3 is not a power of 2.

Similarly we can see that the condition ((n &amp; -n) == n) will always return &#39;true&#39; for a number which is a power of 2 and will always return &#39;false&#39; otherwise.

A close observation will reveal that 2&#39;s complement of a number, which is a power of 2, will always maintain (at the same time it&#39;ll never maintain for a number which is not a power of 2) the significant bit sequence of the corresponding positive number and rest of the bits will be all 1s. Hence a bit-wise AND (&amp;) operator applied on the two (n &amp; -n) will always result into the number (n) itself (as it will maintain the significant bit-sequence and will set rest of the bits to 0s as 0 &amp; 1 = 0). Understood? If not then go through the examples once again and think on the same lines. It should not be that difficult to visualize then.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/2052497357079907134/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-find-whether-number-is-power-of.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/2052497357079907134'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/2052497357079907134'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-find-whether-number-is-power-of.html' title='How to find whether a number is a power of 2 or not in Java?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-3997339654890604057</id><published>2012-10-20T23:10:00.000-07:00</published><updated>2012-10-20T23:10:08.600-07:00</updated><title type='text'>Can we get a different output without changing the main-method definition</title><content type='html'>Can we get a different output without changing the main-method definition?


public class HelloMain {

/**
* @param args
*/
public static void main(String[] args) {
 System.out.println(&quot;Mr. main.&quot;);
}

}


Can we have the output of the above code-segment as &quot;Hi, Mr. main. Bye!&quot; without changing the main-method code?

Yeah, we can have the required output by using &#39;static initializer&#39; blocks effectively. As we know that a static initializer block is called when a class is loaded into memory and hence it&#39;ll obviously run before the main method. Let&#39;s see how this can be used here.

The required output can be broken into three pieces - &quot;Hi, &quot;, &quot;Mr. main.&quot;, and &quot; Bye!&quot;. These parts should get printed in this order only which means the string &quot;Hi, &quot; should be printed before the &#39;println&#39; call inside the main method prints &quot;Mr. main.&quot; and subsequently the last string &quot; Bye!&quot; should be printed.

As we know that &#39;println&#39; method by default ends with a new line and hence to have the last part (&quot; Bye!&quot;) being printed in continuation with the main-method println string, we probably have only two ways:-

    Re-define the default &#39;println&#39; behavior - we can create an anonymous subclass (as we would not be requiring that anywhere else) of the PrintStream class and then re-define the &#39;println&#39; method as per our needs.
    Changing the default line separator - we can use the third part &quot; Bye!&quot; as the new line separator (it can be passed as a command-line argument while calling the class) in which case the &#39;println&#39; of the &#39;main&#39; would print this as the line separator and we will end up getting the required output.

Solution #1: Overriding &#39;println&#39; in a static initializer block in Java


import java.io.PrintStream;

public class HelloMain 
{

 static 
       { 
        // as we are using System.out as the output stream in main 
        final PrintStream currentOut = System.out; 

          // anonymous as we would need this sub class here only 
         PrintStream newOut = new PrintStream(currentOut) 
          { 
              // Overriding &#39;println&#39; method 
              public void println(String string) 
              { 
               
                 // Printing Part - 1 first 
                 print(&quot;Hi, &quot;); 
               
                 //Printing Part -2
                 print(string);

                 // Printing Part - 3, but this should use original &#39;println&#39; def
                 // and hence the usage of &#39;super&#39; comes here. 
                 super.println(&quot; Bye!&quot;); 
              } 
         };

        // Now we are ready with the modified PrintStream and hence setting that 

        System.setOut(newOut);

 }

 /**
    * @param args
      */ 
  public static void main(String[] args) { 
  System.out.println(&quot;Mr. main.&quot;); 
  } 
}


Output: below is the screenshot displaying the output of Solution #1


Solution #2: using an appropriate &#39;line separator&#39; with a static initializer block


public class HelloMain { 
  
    static
 {
  //Printing Part - 1
  System.out.print(&quot;Hi, &quot;);
 } 
   
    /**
      * @param args
      */
    public static void main(String[] args) { 
        System.out.println(&quot;Mr. main.&quot;);  //Printing Part - 2
    } 
}


Part - 3 is printed by changing the default line separator, which is done by setting the string &quot; Bye!&quot; as the new line separator using command line arguments.


java -Dline.separator=&quot; Bye!&quot; HelloMain

</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/3997339654890604057/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/can-we-get-different-output-without.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/3997339654890604057'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/3997339654890604057'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/can-we-get-different-output-without.html' title='Can we get a different output without changing the main-method definition'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-772661922281543866</id><published>2012-10-20T23:08:00.000-07:00</published><updated>2012-10-20T23:08:03.533-07:00</updated><title type='text'>Can we pass a new-line (&#39;\n&#39;) character or any other escape sequence via command line in Java?</title><content type='html'>Can we pass a new-line (&#39;\n&#39;) character or any other escape sequence via command line in Java?

One of our visitors (Vivek Athalye) asked this in response to the article - Tricky use of static initializer block. Thought of posting the answer as a separate article to increase the chances of it reaching to a wider range of audience.

The answer to the query is NO. The question arises, if you pass the same escape sequence programmtically, it works fine, so why doesn&#39;t it work well when passed via command line? For example: System.setProperty(&quot;line.separator&quot;, &quot; Bye!\nBBye!&quot;); will work fine, but if try to do the same via command line as (java -Dline.separator=&quot; Bye!\nBBye!&quot; ClassName) then &#39;\n&#39; will be treated as two distinct ASCII characters (&#39;\&#39; and &#39;n&#39;) and not as a single escape sequence new-line Unicode character.

This behavior was logged as a bug on Sun&#39;s Bug Database on Oct 31, 2003. But, it was closed saying &#39;not a bug&#39; on Nov 05, 2003. The reason given is that interpretation of text passed on command line is a shell specific stuff and it is not reasonable to expect that to work in lines with the handling of escape sequences by any particular programming language.

It&#39;s not something to do with Java as even if you pass a command line argument having &#39;\n&#39; to a C program, it will be treated as two distinct ASCII characters only and not as a escape sequence.

What stops a shell to interpret escape sequences is that escape sequences are represented differently in different programming languages - like &#39;\n&#39; is actually a single character Unicode character whereas in C it&#39;s a two-character ASCII sequence having a different meaning because of the preceding &#39;\&#39; character. So, on a system which requires to run both Java and C programs, which convention should the shell use? Tomorrow, if we see any other representation of escape sequence by some other programming language, how will the already developed shell will cope up with that? Hence, shell plays it straight and simply passes everything written on command line as ASCII character sequences without giving any special meaning to any particular sequence. Fair enough, I believe.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/772661922281543866/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/can-we-pass-new-line-n-character-or-any.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/772661922281543866'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/772661922281543866'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/can-we-pass-new-line-n-character-or-any.html' title='Can we pass a new-line (&#39;\n&#39;) character or any other escape sequence via command line in Java?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-1602710832503687382</id><published>2012-10-20T23:07:00.002-07:00</published><updated>2012-10-20T23:07:30.490-07:00</updated><title type='text'>Finding Caller object, method/class of an instance method in Java</title><content type='html'>Finding Caller object, method/class of an instance method in Java

You might think if we would ever need it? Well... you may never, but no harm in exploring whether we have any/some ways of finding this in Java or not. This question was asked by one of our visitors - Marco Servetto. Thanks Marco for bringing this question up.

For instance methods, by caller you might mean either the object instance of the caller/calling method or method/class name of the caller/calling method. But, for static methods the caller will never be an instance, but only the other two (method/class).

In case of a static method, we don&#39;t have the implicit object reference (this) passed to them as they are never called on instances (even if you call static methods on object references, the call is actually resolved at compile time only and is made on the declared type of the object reference). And hence for them the caller will never be an instance.

If we are interested in finding the object associated with the calling method inside the called method then the most obvious way is to pass the reference &#39;this&#39; to the called method while making the call in the calling/caller method. I doubt if we have any other JVM implementation independent way of doing this. Better to understand it by code, which is pretty simple and straightforward.


public class FindingCallerDemo {

   public static void main(String[] args) {
        new CallerClass().callerMethod();
   }
}
class CallerClass{
   public void callerMethod(){
        Object returnedObj = new CalledClass().calledMethod(this);
        //assert returnedObj == this;
        if (returnedObj == this)
             System.out.println(&quot;Success!&quot;);
        else
             System.out.println(&quot;Failure!&quot;);
   }
}
class CalledClass{
   public Object calledMethod(Object obj){
   return obj;
   }
}


By caller if we mean the name of the caller method name OR the name of the class of the caller method then we can probably use the getStackTrace() method either on current thread instance or on a Throwable instance:

    Using getStackTrace on current thread (since Java 1.5) - &#39;StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()&#39; - we can use this to get the stack trace of the current thread in a StackTraceElemnt array where the first element of the array is the most recent method invocation sequence on the stack - provided the returned array is of non-zero length. StackTraceElement has methods like getClassName, getMethodName, etc., which one can use to find the caller class name or method name.
    Calling getStackTrace on a Throwable instance (since Java 1.4) - creating an instance of Throwable and then calling getStackTrace() method on it, will return an array of StackTraceElement, each of which will contain one stack frame each with the first element containing the most recent inovaction and the last having the least recent. You don&#39;t really need to throw the Throwable instance, only creating one would be good enough here.



StackTraceElement[] ste = new Throwable().getStackTrace();
for (int i = 0; i &lt; ste.length; i++)
 System.out.println(&quot;Class Name: &quot; + ste[i].getClassName()+ &quot;, Method Name: &quot; + ste[i].getMethodName());


Potential Problem: In certain situations, few JVM implementations may either omit one or more stack frames from the stack trace or they might not have any stack frame info at all related to this Throwable instance as a JVM implementation is allowed to return a zero-length array by Java language specs.

Another possible issue is that compile-time inlining may show skewed results. Say if a method A internally calls another method B and B calls C. Let&#39;s suppose the method B has no other executable statement. Obviously this will be a good candidate for compile time inlining as the compiler might replace the call to method B inside method A definition with a call to method C. In such cases, the above two approaches will return the caller method of method C as method A and not as method B what the source code might suggest. Please note that this will require you to turn on the optimization of the compiler. Results may vary across compilers as different compilers may have different criteria for inlining - some might never do.

Other Possible Solutions: there can be some other possible solutions using a native method (like getCallerClass method) of some JVM implementation specific classes. We should avoid such a practice as we may otherwise sacrifice the portability of the code. Even worse, in case the implementation specific class is non-public then you might not use your code on the changed version of the same JVM implementation itself.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/1602710832503687382/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/finding-caller-object-methodclass-of.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/1602710832503687382'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/1602710832503687382'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/finding-caller-object-methodclass-of.html' title='Finding Caller object, method/class of an instance method in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-6658575008097983452</id><published>2012-10-20T23:06:00.003-07:00</published><updated>2012-10-20T23:06:56.236-07:00</updated><title type='text'>How to pick access control modifier for fields in Java?</title><content type='html'>How to pick access control modifier for fields in Java?

For fields, the thumb rule is quite simple - make all instance fields &#39;private&#39; and have getters/setters to access/modify them. However, you would probably like to make most of your static fields as &#39;public&#39; as they are class variables and meant to be accessed from outside either on the class name (preferred way) or on any instance.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/6658575008097983452/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-pick-access-control-modifier-for.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6658575008097983452'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6658575008097983452'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/how-to-pick-access-control-modifier-for.html' title='How to pick access control modifier for fields in Java?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-1775602429454858265</id><published>2012-10-20T23:06:00.001-07:00</published><updated>2012-10-20T23:06:30.248-07:00</updated><title type='text'>When to pick &#39;private&#39; access control modifier?</title><content type='html'>When to pick &#39;private&#39; access control modifier?

&#39;private&#39; is something private to your class and hence you have no commitment towards others. You can change them anytime you want as long as it doesn&#39;t hurt the functioning of any public/protected/default member.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/1775602429454858265/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-private-access-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/1775602429454858265'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/1775602429454858265'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-private-access-control.html' title='When to pick &#39;private&#39; access control modifier?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-4491360040388752878</id><published>2012-10-20T23:05:00.007-07:00</published><updated>2012-10-20T23:05:56.184-07:00</updated><title type='text'>When to pick default access control modifier?</title><content type='html'>When to pick default access control modifier?

&#39;package-private&#39; or the default access control modifier puts you under only one commitment. This is towards all the classes in the same package as they will have access to all your package-private members and hence they can have their implementation dependent on those members.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/4491360040388752878/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-default-access-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/4491360040388752878'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/4491360040388752878'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-default-access-control.html' title='When to pick default access control modifier?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-8344768748648843706</id><published>2012-10-20T23:05:00.004-07:00</published><updated>2012-10-20T23:05:29.845-07:00</updated><title type='text'>When to pick &#39;protected&#39; as the access control specifier?</title><content type='html'>When to pick &#39;protected&#39; as the access control specifier?

A &#39;protected&#39; modifier specifies that the member can be accessed from within the same package as well as by a sub-class in some other package.

Let&#39;s pick the suitable access modifier for a member which you want any of your sub-classes to have access to. Of course you can&#39;t choose &#39;private&#39; here as the access will then be limited to your class only. Next up the ladder is &#39;package-private (default)&#39; which will restrict the access limited to all the classes (either a sub class or not) in the same package only. But, if you want any sub class of your class to access the member then the default access modifier won&#39;t do it for you. Next up the ladder is &#39;protected&#39; which suits fine here so no need to go further up. Quite simple to pick the suitable access modifier, isn&#39;t it?

Making something &#39;protected&#39; also puts you in some sort of commitment in case you are not making your class as &#39;final&#39; as otherwise the sub-classes of your class may write their implementation based on the availability of your &#39;protected&#39; member. You have to be careful with the fact that the &#39;protected&#39; members can be used by any class in the same package, so even if you have made your class as &#39;final&#39; the commitment to make the &#39;protected&#39; members available to all the classes in the same package still remains. But, why would you come up with such a design? If you want the member to be accessible only from within the same package, better make it package-private (default). Making a class &#39;final&#39; which is having &#39;protected&#39; members would certainly draw attention as to why would anyone like to do it. You would better need to review the class design in such a case.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/8344768748648843706/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-protected-as-access.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/8344768748648843706'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/8344768748648843706'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-protected-as-access.html' title='When to pick &#39;protected&#39; as the access control specifier?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-5665778413155995851</id><published>2012-10-20T23:05:00.001-07:00</published><updated>2012-10-20T23:05:03.190-07:00</updated><title type='text'>When to pick &#39;public&#39; as the access control modifier?</title><content type='html'>When to pick &#39;public&#39; as the access control modifier?

How do you normally go about choosing the access specifier/modifier of a method in your class definition - whether you start from &#39;public&#39; and move on to &#39;private&#39; to see which specifier would actually suit the requirements or do you go about the other way round? It probably makes more sense to go the other way - starting from &#39;private&#39; and moving onto &#39;public&#39;. There should be a very strong reason why you would need a method to make &#39;public&#39; as it would then become a part of the public interface of the class - a commitment from the class designer to all (those who are already consuming or those who would be consuming in future).

Therefore, choosing &#39;public&#39; as the access specifier should be given a thorough review as consumers of the class can (which they normally do) use them in their implementation and hence once you make something public you got to support that for the consumers of your class till eternity (making a &#39;public&#39; member deprecated and subsequently getting rid of it will be a difficult and time consuming exercise). A big ask especially in a professional environment where your class is being consumed by many critical applications. So as a thumb rule make only those members &#39;public&#39;, which you can&#39;t make either &#39;private&#39;, &#39;package-private (default)&#39; or &#39;protected&#39;.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/5665778413155995851/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-public-as-access-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5665778413155995851'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5665778413155995851'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/when-to-pick-public-as-access-control.html' title='When to pick &#39;public&#39; as the access control modifier?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-2600337291363437810</id><published>2012-10-20T23:04:00.005-07:00</published><updated>2012-10-20T23:04:42.331-07:00</updated><title type='text'>Choosing suitable access control modifier for methods in Java?</title><content type='html'>Choosing suitable access control modifier for methods in Java?

Here I&#39;m assuming that your top-level (i.e., a class which is not nested) class is &#39;public&#39; as otherwise if it&#39;s having the default access control modifier then you would probably never make any member public or protected owning to the fact the class itself can&#39;t be used outside the package. </content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/2600337291363437810/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/choosing-suitable-access-control.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/2600337291363437810'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/2600337291363437810'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/choosing-suitable-access-control.html' title='Choosing suitable access control modifier for methods in Java?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-6121438156018621666</id><published>2012-10-20T23:04:00.002-07:00</published><updated>2012-10-20T23:04:22.114-07:00</updated><title type='text'>Access Control Modifiers available for classes and members in Java</title><content type='html'>Access Control Modifiers available for classes and members in Java

Top-level classes in Java can have only two access control modifiers - public and default (package-private) whereas the members have four access control modifiers - public, protected, default (package-private), and private. Nested Classes are treated as members of the top-level classes so all four access control modifiers are applicable to them.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/6121438156018621666/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/access-control-modifiers-available-for.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6121438156018621666'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6121438156018621666'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/access-control-modifiers-available-for.html' title='Access Control Modifiers available for classes and members in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-7301649021194696018</id><published>2012-10-20T23:03:00.004-07:00</published><updated>2012-10-20T23:03:41.627-07:00</updated><title type='text'>Static Initialization Blocks and their alternatives in Java</title><content type='html'>Static Initialization Blocks and their alternatives in Java

Why do we need Static Initialization Blocks?

The easiest way of initializing fields (static or instance) in Java at the time of their declaration is simply by providing a compile time constant value of a compatible data type. For example:


public class InitializationWithConstants{

public static int staticIntField = 100;
private boolean instanceBoolField = true;

}


This type of initialization has its limitation due to its simplicity and it can not support initialization based even on some moderately complex logic - like initializing only selected elements of a complex array using some logic in a for loop.

Here comes the need for static initialization blocks and initializer blocks for initializing static and instance fields, respectively.

Static Initialization Blocks - what are they and how to use them?

It&#39;s a normal block of code enclosed within a pair of braces and preceded by a &#39;static&#39; keyword. These blocks can be anywhere in the class definition where we can have a field or a method. The Java runtime guarantees that all the static initialization blocks are called in the order in which they appear in the source code and this happens while loading of the class in the memory.


public class InitializationWithStaticInitBlock{

public static int staticIntField;
private boolean instanceBoolField = true;

static{
 //compute the value of an int variable &#39;x&#39;
 staticIntField = x;
}
}


Since static initialization blocks are actually code-blocks so they will allow us to initialize even those static fields which require some logical processing to be done for them to get their initial values.

Alternative to Static Initialization Blocks

A private static method is a suitable alternative to the static initialization blocks. In fact it has some advantages over static initialization blocks as well like you can re-use a private static method to re-initialize a static field in case you need it. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a &#39;public&#39; static method can&#39;t do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method &#39;public&#39;. More about how to pick the access control modifiers here - Choosing a suitable access control modifier &gt;&gt;


public class InitializationWithPrivateStaticMethod{

public static int staticIntField = privStatMeth();
private boolean instanceBoolField = true;

private static int privStatMeth() {
 //compute the value of an int variable &#39;x&#39;
 return x;
}
}
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/7301649021194696018/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/static-initialization-blocks-and-their.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/7301649021194696018'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/7301649021194696018'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/static-initialization-blocks-and-their.html' title='Static Initialization Blocks and their alternatives in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-742193103173881622</id><published>2012-10-20T23:03:00.001-07:00</published><updated>2012-10-20T23:03:08.476-07:00</updated><title type='text'>Initializer Blocks in Java and their possible alternatives</title><content type='html'>Initializer Blocks in Java and their possible alternatives

Initializer Blocks - what are they, why &amp; how are they used?

These blocks are similar to the static initialization blocks with the only difference being the absence of the &#39;static&#39; keyword. The Java compiler copies all the initializer blocks in the same order as they are in the source code in every constructor before any executable statement in that constructor.


public class InitializationWithInitializerBlock{

public static int staticIntField = 100;
private boolean instanceBoolField;

{
     boolean y;
           
     y = true; //or, y = &lt;some expression returning a boolean value&gt;;

     instanceBoolField = y;
}
}


So if you see all your constructors having same code-segment at the top then you will probably be better off keeping that in an initializer block as anyway the compiler would copy the block in every constructor at the top. This way you can at least make the code more readable, maintainable (as the common code will only be at one place), and if the size of common code is significant and if you have multiple constructors then using initializer block you can also reduce the size of your source code.


public class InitializerBlocks {

public static void main(String[] args) {
new InitializerBlocks();
}
//Constructor - 1
public InitializerBlocks(){
System.out.println(&quot;3&quot;);
}
//Initializer Block - 1
{
System.out.println(&quot;1&quot;);
}
//Initializer Block - 2
{
System.out.println(&quot;2&quot;);
}
}

Output

1
2
3

(Of course the above code is not making a good use of initializer blocks as they not initializing anything what they are actually meant to. The purpose here is just to show how a Java compiler places all the initializer blocks at the top in every constructor in the same order as they appear in the code.)

Alternative to Initializer Blocks in Java

You can use an instance method to initialize an instance field - in most of the cases you would like to make this instance method as &#39;final&#39; as there will hardly be any need for the subclasses to override such a method (evidently, a non-final instance method would also do the job). Similarly if you need to call the method only from within the same class, you would probably make it &#39;private&#39;. Read more about how to pick access modifiers - choosing suitable access control modifiers in Java &gt;&gt;


public class InitializationWithPrivateInstanceMethod{

public static int staticIntField = 100;
private boolean instanceBoolField = privInstanceMeth();

private final boolean privInstanceMeth() {
     boolean y;
     //computing the value of y
     y = &lt;some expression returning boolean&gt;;
     return y;
}
}


The advantage of using an instance method over an initializer block is that it gives you flexibility of re-initializing those instance fields by calling the corresponding final instance method(s) in some setter or in some other method. Another interesting scenario where you can&#39;t use an initializer block and you would probably need an instance method to do it for you: Suppose you have a need of using the code of initializer block in any of your sub-classes and suppose all your constructors have extra code as well in addition to the initializer block code which would be added to them on the top during compilation. Now in such a situation, if you need to set only those fields which are set in the initializer block then you can&#39;t do that directly in your subclass as the most you can do here is to call a super class constructor (that too would normally re-set all the instance fields) ... right? Having a final instance method would solve your problem here. Choosing a suitable access specifier will again follow the same rules what has been discussed in article mentioned in above paragraph. In this case since the sub-classes require access to that method, so choosing &#39;protected&#39; as the access specifier should be fine</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/742193103173881622/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/initializer-blocks-in-java-and-their.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/742193103173881622'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/742193103173881622'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/initializer-blocks-in-java-and-their.html' title='Initializer Blocks in Java and their possible alternatives'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-5966666460251845481</id><published>2012-10-20T23:01:00.000-07:00</published><updated>2012-10-20T23:01:11.782-07:00</updated><title type='text'>Tricky Method Overloading</title><content type='html'>Tricky Method Overloading

Let&#39;s start with looking at a code-segment and try to think of the output/error, it would produce when compiled/executed and subsequently we&#39;ll discuss the behavior of code.


public class NullTest {

   public static void method(Object obj){
     System.out.println(&quot;method with param type - Object&quot;);
   }
 
   public static void method(String obj){
     System.out.println(&quot;method with param type - String&quot;);
   }
 
   public static void main(String [] args){
     method(null);
   }
}


So, what do you expect as the output here? Before thinking about the output, do you really expect the code to compile successfully? Well... yeah, the code will compile and run fine as opposed to anyone who might have sensed an ambiguity here - we&#39;ll see the reason soon.

Since the methods are overloaded, the resolution will be done at compile-time only. Which method do you see being bind here - the one with parameter type &#39;Object&#39; or the one with parameter type &#39;String&#39; and why? Of course, the compiler can&#39;t bind two methods with one call, so on what basis would it pick the most suitable? Which method would be picked, is evident from the output given below:-


method with param type - String


Any guesses for why a special treatment is being given to &#39;String&#39; here? Well... it&#39;s not actually for &#39;String&#39; class specifically, but any sub-class would get a preference over the super class in such a situation. But, why? Because JLS (Section: 15.12.2.5) allows this. It clearly says:

&quot;If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.&quot;

As you easily deduce that the compiler should be able to pick &#39;the most specific&#39;, failing which it will throw a compile-time error. Let&#39;s understand it with the below code-segment which doesn&#39;t compile because the compiler can&#39;t pick &#39;the most specific&#39; here.


public class NullTest {

   public static void method(Object obj){
     System.out.println(&quot;method with param type - Object&quot;);
   }
 
   public static void method(String str){
     System.out.println(&quot;method with param type - String&quot;);
   }
 
   public static void method(StringBuffer strBuf){
     System.out.println(&quot;method with param type - StringBuffer&quot;);
   }
 
   public static void main(String [] args){
     method(null); //... compile-time error!
   }
}


Why is the compiler not able to pick &#39;the most specific&#39; here - because both String and StringBuffer are are sub-classes of the Object class, but without being in the same inheritance hierarchy. For finding &#39;the most specific&#39; method, the compiler needs to find a method having the parameter type, which is a sub-class of the parameter types of all other overloaded methods.

This holds true for overloaded methods having more than one parameters as well. The compiler would pick &#39;the most specific&#39; by looking which method is having at least one of its parameter types as a clear sub-class of the corresponding parameter type and other parameter types being either the same or clear sub-classes, in all other overloaded methods. If it can find one, good, otherwise it will throw a compile-time error. For example:


public class NullTest {

 public static void method(Object obj, Object obj1){
   System.out.println(&quot;method with param types - Object, Object&quot;);
 }

 public static void method(String str, Object obj){
   System.out.println(&quot;method with param types - String, Object&quot;);
 }

 public static void main(String [] args){
   method(null, null);
 }
}

Output

method with param types - String, Object


In this case the compiler can easily pick &#39;the most specific&#39; as the method having parameter types (String, Object) as the other overloaded method is having its parameter types as (Object, Object) - clearly &#39;String&#39; is a subclass of &#39;Object&#39; and the other parameter is of same type, so the method with parameter types (String, Object) can be picked with ease. But, the below code would throw a compile-time error as none of the methods satisfy the condition for being picked as &#39;the most specific&#39; method.


public class NullTest {

 public static void method(Object obj, String obj1){
   System.out.println(&quot;method with param types - Object, String&quot;);
 }

 public static void method(String str, Object str1){
   System.out.println(&quot;method with param types - String, Object&quot;);
 }

 public static void main(String [] args){
   method(null, null); //... compile-time error!
 }
}


Before I conclude let me thank Ranvijay (one of our regular visitors), who inquired about the underlying reason of this behavior via an email. I thought it would probably be helpful to other visitors as well and hence posted a full article. Keep contributing Ranvijay!</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/5966666460251845481/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/tricky-method-overloading.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5966666460251845481'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5966666460251845481'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/tricky-method-overloading.html' title='Tricky Method Overloading'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-556582680546945438</id><published>2012-10-20T22:59:00.002-07:00</published><updated>2012-10-20T22:59:44.655-07:00</updated><title type='text'>Concurrent execution of static and non-static synchronized methods</title><content type='html'>Concurrent execution of static and non-static synchronized methods


We have a scenario where we have a static synchronized method and a non-static synchronized method. As we know that a static method can only access static members of the class whereas a non-static method can access both static as well as non-static members. This liberty can put us into a situation where a non-static method might be updating some static data which a static method would also be changing. What will happen if two different threads try to access the static and non-static synchronized methods concurrently and in turn try to change the static data using the two methods? Will the synchronization guarantee mutual exclusion in such a case?


No... synchronization won&#39;t guarantee mutual exclusion in such a case as both the threads may access the static and non-static synchronized methods concurrently because a non-static synchronized method requires the invoking thread to acquire a lock of the particular object on which the thread invokes the non-static synchronized method whereas a static synchronized method will require the invoking thread to acquire a lock on the java.lang.Class object associated with the particular class (which the static method is a part of). Both these locks have nothing to do with each other and they can be acquired by different threads at the same time and hence two different threads may execute a static method and a non-static synchronized method of a class respectively at the same time (of course once they acquire the two locks).


It is certainly not advisable to allow such a thing to happen and hence the design of such a class needs to be re-checked. Otherwise the errors caused by simultaneaous modification of the same static data by different threads may infuse some really-hard-to-detect bugs.


Thus, we see that only declaring the methods as synchronized doesn&#39;t ensure mutual exclusion and the programmer should always think about the locks involved to achieve the actual purpose of synchronization.


Have a look at the following simple example where the same static data is being modified by two public synchronized methods - one being static and the other being non-static. The whole purpose of synchronization is getting defeated here as in such a case mutual exclusion can&#39;t be guaranteed, which is one of main purposes of using synchronization.


public final class BadDesign{

private static int sensitiveData;

public synchronized static void changeDataViaStaticMethod(int a){

//... updating the sensitiveData

sensitiveData = a;

}


public synchronized void changeDataViaNonStaticMethod(int b){

//... updating the sensitiveData

sensitiveData = b;

}


public static void showSensitiveDataStatic(){

System.out.println(&quot;Static: &quot; + Thread.currentThread().getName()+ &quot; - &quot; + sensitiveData);

}


public void showSensitiveData(){

System.out.println(Thread.currentThread().getName() + &quot; - &quot; + sensitiveData);

}


public static void main(String[] args){

new Thread(new TestThread11()).start();

new Thread(new TestThread11()).start();

}


}


class TestThread11 implements Runnable{


public void run(){

int i = 0;

do{

BadDesign.changeDataViaStaticMethod(5);

BadDesign.showSensitiveDataStatic();


//... new object for every iteration

//... so synchronization of non-static method

//... doesn&#39;t really do anything significant here

BadDesign bd = new BadDesign();

bd.changeDataViaNonStaticMethod(10);

bd.showSensitiveData();

}while (i++ &lt; 100);

}

}


An excerpt from the output:-

...

Static: Thread-0 - 5

Thread-0 - 10

Static: Thread-0 - 5

Thread-0 - 10

Thread-1 - 10

Static: Thread-0 - 5

Static: Thread-1 - 5

Thread-1 - 10

...


By looking at the above exceprt you can easily conclude that the static and non-static synchronized method calls are intermixed between the two threads: Thread-0 and Thread-1. In this case the non-static synchronized method is always being called on a new object (as the do-while loop of the run() method is creating a new object of the class BadDesign for every non-static synchronized method call) by both the threads and hence synchronization doesn&#39;t really do anything significant for them as every new object will have its own lock which will be easily acquired by the invoking thread everytime the do-while loop iterates. I&#39;ve kept this just to make the code simple as my purpose of the above example is just to show that static synchronized methods and non-static synchronized methods are completely independent of each other and both of them can run at the same time by different threads for the simple reason that both these methods are governed by different locks which may be acquired at the same time by two different threads.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/556582680546945438/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/concurrent-execution-of-static-and-non.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/556582680546945438'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/556582680546945438'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/concurrent-execution-of-static-and-non.html' title='Concurrent execution of static and non-static synchronized methods'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-6371144146363543521</id><published>2012-10-20T22:58:00.004-07:00</published><updated>2012-10-20T22:58:56.760-07:00</updated><title type='text'>What&#39;s Deadlock?</title><content type='html'>Deadlock 


What&#39;s Deadlock?


It&#39;s basically a situation where two or more threads are blocked forever waiting for each other to release an acquired monitor to proceed further.


Let me try to explain it using an example. Suppose we have two thread - threadA and threadB. There are two objects of a class TestClass - objA and objB and we have two synchronized instance methods in TestClass named A and B. Method A accepts an argument of type TestClass and calls method B from the passed object reference. Now, consider a situation where the first thread - threadA acquires the monitor of objA and enteres into the synchronized method A() on objA with the passed object reference as objB and at the same time threadB enteres into the same synchronized method &#39;A&#39; on the object reference - objB with the passed object reference to the method as objA. Now, both the threads will keep waiting for the monitors of the objects - objB and objA respectively to complete the execution of the synchronized method A() and hence such a situation will result into a Deadlock. Of course such a situation will probably happen only rarely, but it&#39;s definitely a possible scenario. Calling the start() method on a Thread instance only ensures that the particular thread will participate in the CPU Scheduling, but we never know when exactly the thread will actually be allocated the CPU and in turn will start the execution.


Example: Java program having a possibility of Deadlock


public class PossibleDeadlockDemo {


static class TestClass {

...

...


public synchronized void A (TestClass testClass) {

...

testClass.B();

}


public synchronized void B () {

...

}

}


public static void main(String[] args) {

final TestClass objA = new TestClass(&quot;ObjectA&quot;);

final TestClass objB = new TestClass(&quot;ObjectB&quot;);


Thread threadA = new Thread(new Runnable() {

public void run() { objA.A(objB); } });


Thread threadB = new Thread(new Runnable() {

public void run() { objB.A(objA); } });


threadA.start();

threadB.start();

}


}


How to deal with a Deadlock situation?


Probably the only possible way to rectify a Deadlock situation is to avoid it. Once the deadlock has already happened then you&#39;ll probably left with the only option of restarting the JVM process again OR it may even require you to restart the underlying OS. This is very hard to reproduce and debug because one can never be sure about when exactly the threads will be executed and hence the deadlock may not happen when you test it and eventually it may happen when the code actually goes into production. So, review the design of your mulithreaded application before you really start coding. You may somehow manage to escape any such situation or at least minimize the possibility to a great extent with a better design.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/6371144146363543521/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/whats-deadlock.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6371144146363543521'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6371144146363543521'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/whats-deadlock.html' title='What&#39;s Deadlock?'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-3037554714690243443</id><published>2012-10-20T22:58:00.000-07:00</published><updated>2012-10-20T22:58:02.492-07:00</updated><title type='text'>Guarded Blocks in Java </title><content type='html'>Guarded Blocks in Java 

This is one of the most popular mechanisms of co-ordinating the execution of multiple threads in a multithreaded application. Such a block keeps checking for a particular condition to become true and only in that case the actual execution of the thread resumes.

Why should a thread&#39;s execution required to be co-ordinated with that of other threads? There may be several reasons - one of them being, if multiple threads are modifying a shared data and one (or maybe more) threads can&#39;t really proceed unless the shared data acquires a particular value (otherwise the execution may cause some incosistency/business-error or something of that sort) then in such a case we can have a condition checking the value of that shared data in that particular thread and can allow the execution of the thread to proceed only when the condition is true.

Now what the thread will do until then? Based on how the thread reacts to a &#39;false&#39; condition, guarded blocks are of two types:-

    synchronized guarded block - in this case if the condition is false then the block (which is a synchronized block) simply calls the Object.wait() method to release the acquired monitors on that object and leaves the processor to be used by other threads (probably more effectively as the current thread would not have done anything significant in this case unless the condition becomes true).
    non-synchronized guarded block - in this case we simply cause the execution to keep executing a blank loop until the condition becomes true. This approach has an obvious disadvantage of wasting the precious CPU time, which could have been better utilized by some other threads otherwise.


Example: synchronized guarded block - Java code snippet

public synchronized guardedBlock() {

while(!sharedBooleanFlag) {
try {
wait();
} catch (InterruptedException e) {}
}

System.out.println(&quot;Shared Boolean Flag is true - you may proceed now!&quot;);

}

non-synchronized guarded block - Java code snippet

public guardedBlock() {

while(!sharedBooleanFlag) {
//... empty loop
}

System.out.println(&quot;Shared Boolean Flag is true - you may proceed now!&quot;);

}

A thread which is in waiting state on an object may be interrupted/notified by some other thread either intentionally or accidentally and hence may start execution after getting re-scheduled, but that doesn&#39;t guarantee that the condition (which is required to be true for the thread to proceed further) has also become true and hence one needs to make sure that the wait() method is always called inside the loop which checks for the condition. If the thread wakes up and starts its execution before the condition becomes true then it&#39;ll immediately go to the waiting state once again which will obviously save the precious CPU time to be utilized by other threads and at the same time such an approach will always guarantee that the execution of the thread will proceed only in the expected manner.

Don&#39;t forget to ensure that the application has other threads which acquire locks on the objects (on which few other threads have previously called wait() method) and call either notify() and notifyAll() methods so that the application can avoid startvation of those threads which have called wait() on the objects under consideration. notifyAll() scheduled all the waiting threads whereas notify() randomly picks one of the waiting threads and schedules it. Use the method which suits the design of your application</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/3037554714690243443/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/guarded-blocks-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/3037554714690243443'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/3037554714690243443'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/guarded-blocks-in-java.html' title='Guarded Blocks in Java '/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-5151211608885840680</id><published>2012-10-20T22:56:00.002-07:00</published><updated>2012-10-20T22:56:42.743-07:00</updated><title type='text'>ThreadLocal in Java</title><content type='html'>ThreadLocal in Java

As the name suggests this Java library class is used for supporting thread-local variables - the variables which are local to the particular thread instance and hence each thread will have their own copy of such variables which will be initialized every time a new thread is spawned.

To be more clear, let&#39;s take one simple example. If you have a class having some private/public static fields defined in it then all the objects created in all threads will share the same instances of those static fields. What if you want every thread to have a separate copy of it? ThreadLocal class will be of use in such cases, in fact they are mainly used for this purpose only. You can&#39;t just switch to a non-static field as in that case all the objects (even those created in the same thread) will have their own copies. You may come across situations asking you to have copies based on threads and not based on instances. This is where you will probably like to use ThreadLocal.

This class was introduced to Java in the version 1.2 and it has only three methods - one protected (initialValue()) and two public (get() and set()). The method set() is only rarely used as for most of the applications use the initialValue() method does the trick.

    protected Object initialValue() - as the name suggests this method returns the initial value of the ThreadLocal variable for the current thread and it&#39;s invoked at most once per thread. This method will be executed only if the thread calls the get() method on the ThreadLocal variable for the time and also only if the thread doesn&#39;t call set() method on the ThreadLocal variable prior to calling get() on it. As already mentioned that initialValue() method is called only when get() is called for the first time and hence if the thread calls set() method before get() then the initialValue() will never be executed on that ThreadLocal variable.
    public Object get() - evidently it will return the value of the ThreadLocal variable for the current thread. As discussed above, if it&#39;s called for the first time then the ThreadLocal variable is created and initialized by calling the initialValue() method internally.
    public void set(Object value) - like any other setter this method will also set the current thread&#39;s copy of the ThreadLocal variable to the passed &#39;value&#39;. This method is used only rarely as in most of the cases initialValue() method solves the purpose in a better way.


initialValue() method v/s set() method for a ThreadLocal variable

    initialValue() method is called at most once and it&#39;s called only implicitly whereas set() method can be called any number of times and every time the call will be an explicit call.
    initialValue() is called when get() method is called for the first time on the ThreadLocal variable in the current thread and that too only when set() method has not been called before the first get() call (in which case initialValue() method is never called in that thread on that ThreadLocal variable).


Overriding the initialValue() method and using it in an application

initialValue() method is a protected method which initializes the ThreadLocal variable with &#39;null&#39; in its default implementation and almost every time we need to override this method to initialize the ThreadLocal variable as per our requirements. Anonymous inner classes are normally used for this overriding to make the code more readable and maintainable. Let&#39;s walk through the sample code given in the Sun Javadoc for ThreadLocal.


public class SerialNum {
 // The next serial number to be assigned
 private static int nextSerialNum = 0;

 private static ThreadLocal serialNum = new ThreadLocal() {
     protected synchronized Object initialValue() {
         return new Integer(nextSerialNum++);
     }
 };

 public static int get() {
     return ((Integer) (serialNum.get())).intValue();
 }
}


In the above example, changes made to the private static int field named &#39;nextSerialNum&#39; will be reflected in all the threads using the &#39;SerialNum&#39; class as it&#39;s a normal static field and will be shared across all the instances created in all the threads, but the static ThreadLocal field named &#39;serialNum&#39; will be created and maintained separately for all the threads and will not be shared across all the threads.

As you can see that anonymous inner class has been used to override the initialValue() method which sets the initial value of the ThreadLocal variable &#39;serialNum&#39; to the Integer object created with the current value of the static field &#39;nextSerialNum&#39;.

A call to the get method of the &#39;SerialNum&#39; class will ultimately call the get() method on the ThreadLocal variable &#39;serialNum&#39; and if the first outer get (of the SerialNum class) call will obviously make the first inner get (of the ThreadLocal class) call on the ThreadLocal instance &#39;serialNum&#39; which will subsequently invoke the initialValue() on the ThreadLocal variable in the current thread.

InheritableThreadLocal - what&#39;s this and when to use it?

Suppose you have a requirement of setting the value of a ThreadLocal variable in a child thread as a function of the value of a ThreadLocal variable in the parent thread, then using a normal ThreadLocal variable won&#39;t do the needful as for ThreadLocal variables the initial values are set independently in every thread including any child threads as well.

InheritableThreadLocal which subclasses ThreadLocal class is used in such situations. This class has only one method &#39;protected Object childValue(Object parentValue)&#39; which is used to set the initial value of the InheritableThreadLocal variable in the child thread as a function of a ThreadLocal variable (passed as a parameter) in the parent thread. This method is called from within the parent thread before the child thread is created and the default implementation will make the child values identical to parent&#39;s, but we can override the childValue() method to set the child value as a function of the parent value for those ThreadLocals which have values in the parent thread. By default the childValue() returns the same input argument, but again an override of the childValue method might change this behavior as well.</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/5151211608885840680/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/threadlocal-in-java.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5151211608885840680'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5151211608885840680'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/threadlocal-in-java.html' title='ThreadLocal in Java'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-5539349258176799571</id><published>2012-10-20T22:55:00.002-07:00</published><updated>2012-10-20T22:55:51.934-07:00</updated><title type='text'>per-thread Singleton and per-thread Logging</title><content type='html'>Usage of ThreadLocal: per-thread Singleton and per-thread Logging

Should you require a refresh of what ThreadLocals in Java are and how they work, refer to this article first. You can then proceed with the current article for understanding two of the most common uses of ThreadLocals in Java.

per-thread Singleton impl using ThreadLocal

Suppose you have a need of having a JDBC Connection objects per thread of your application. The moment you hear the term &#39;per-thread&#39;, ThreadLocal automatically comes into mind as that&#39;s what it&#39;s primarily meant for. Below is a sample implementation of how easily can you actually use ThreadLocal for a per-thread JDBC Connection object in Java.


public class ConnectionDispenser {

 private static class ThreadLocalConnection extends ThreadLocal {

   public Object initialValue() {

     return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());

   }

 }

 private static ThreadLocalConnection conn = new ThreadLocalConnection();

 public static Connection getConnection() {

   return (Connection) conn.get();

 }

}


Most of the code is self-explanatory and you can easily see how overriding the &#39;initialValue()&#39; method of ThreadLocal is doing the trick of getting a Connection object by calling &#39;getConnection&#39; method of the &#39;DriverManager&#39; class. As you know the &#39;initialValue()&#39; method is called only once for a ThreadLocal object and hence the Connection object will be obtained only once per thread (as a ThreadLocal object is created per thread only). From then on, whenever the particular thread requires the Connection object it simply calls the static &#39;getConnection&#39; method of the your &#39;ConnectionDispenser&#39; class, which in turn calls the &#39;get()&#39; method of ThreadLocal to fetch the Connection object associated with that particular thread.

per-thread Debug Logging impl using ThreadLocal

Ever thought of having a per-thread DEBUG logging for any of your applications? Few multi-threading applications do get trickier at times and having per-thread DEBUG logs might be of great help in such situations as you probably can&#39;t visualize the actual order in which the threads might have executed and changed the shared objects. Here goes a sample implementation of per-thread DEBUG logging in Java using ThreadLocal.


public class DebugLogger {

 private static class ThreadLocalList extends ThreadLocal {

   public Object initialValue() {

     return new ArrayList();

   }

   public List getList() {

     return (List) super.get();

   }

 }


 private ThreadLocalList list = new ThreadLocalList();

 private static String[] stringArray = new String[0];


 public void clear() {

   list.getList().clear();

 }


 public void put(String text) {

   list.getList().add(text);

 }


 public String[] get() {

   return list.getList().toArray(stringArray);

 }

}


As you can identify we are using an ArrayList object to store the logging info for a thread. &#39;initialValue&#39; has been overridden to initialize every thread with a new ArrayList object. Whenever your multi-threaded application calls the &#39;put&#39; method of your &#39;DebugLogger&#39; class then all that method does is that it adds the logging info (passed as an String parameter to the &#39;put&#39; call) to the corresponding ArrayList object of the current thread. Similarly a &#39;get&#39; call of your &#39;DebugLogger&#39; class simply returns the associated ArrayList object of the current thread in form of an String array. Evidently the &#39;clear&#39; method of your &#39;DebugLogger&#39; class is for clearing the logging info captured so far for the current thread - it&#39;ll simply clear the ArrayList object holding logging info for the current thread. This might help you getting rid of the non-essential logging info, maybe based on some condition, when you know for sure that all that you need for your debugging is what you are going to capture next and now what has already been captured so far.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/5539349258176799571/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/per-thread-singleton-and-per-thread.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5539349258176799571'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/5539349258176799571'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/per-thread-singleton-and-per-thread.html' title='per-thread Singleton and per-thread Logging'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7450758598965295876.post-6827715450365971399</id><published>2012-10-20T22:54:00.003-07:00</published><updated>2012-10-20T22:54:53.579-07:00</updated><title type='text'>wait(), notify() and notifyAll() methods have been defined in the Object class</title><content type='html'>wait(), notify() and notifyAll() methods have been defined in the Object class

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type &#39;Object&#39;), not only with Threads.

wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a &#39;telephone&#39; object, which at one point of time can be used by only one thread. Like every other object in Java, &#39;telephone&#39; object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the &#39;telephone&#39; object requires activation before it can be used and suppose only a few admin threads can activate the &#39;telephone&#39; object.

As soon as a thread needs access to the &#39;telephone&#39; object, it checks if the lock on that &#39;telephone&#39; object is available or not, if yes, it acquires that and checks if the &#39;telephone&#39; is active or not. If yes, it starts using it otherwise it calls &#39;wait()&#39; on the telephone object which effectively releases the monitor of the &#39;telephone&#39; object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the &#39;telephone&#39; object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.

Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the &#39;telephone&#39; object and eventually activates it and subsequently calls &#39;notify()&#39; or &#39;notifyAll()&#39; on the &#39;telephone&#39; object. &#39;notify()&#39; will simply pick one of the threads from the wait-set of the &#39;telephone&#39; object (which one will be picked is an implementation dependent stuff and Java Language specification doesn&#39;t enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the &#39;telephone&#39; object along with any other thread that might be vying to access the &#39;telephone&#39; at that point of time.

The only difference between &#39;notify&#39; and &#39;notifyAll&#39; is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.

Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the &#39;object&#39; (in our case &#39;telephone&#39;) is the particular object&#39;s prerogative and not that of the requester threads&#39;. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn&#39;t find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object&#39;s level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won&#39;t be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.
</content><link rel='replies' type='application/atom+xml' href='http://studentsinform.blogspot.com/feeds/6827715450365971399/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://studentsinform.blogspot.com/2012/10/wait-notify-and-notifyall-methods-have.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6827715450365971399'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7450758598965295876/posts/default/6827715450365971399'/><link rel='alternate' type='text/html' href='http://studentsinform.blogspot.com/2012/10/wait-notify-and-notifyall-methods-have.html' title='wait(), notify() and notifyAll() methods have been defined in the Object class'/><author><name>Unknown</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='https://img1.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>