Friday, 29 June 2012

Google Guava Cache

Guava Cache offers more flexibility and power than either a HashMap or ConcurrentHashMap, but is not as heavy as using EHCache or Memcached (or robust for that matter, as Guava Cache operates solely in memory).

A method you won’t find is ‘put’, because Guava Cache is ‘self-populating’, values that aren’t present when requested are fetched or calculated, then stored. There is another method ‘asMap’ that exposes the entries in the cache as a thread safe map.

Initially we are going to spend the bulk of the time talking about CacheLoader and CacheBuilder. CacheLoader specifies how to load values, and CacheBuilder is used to set the desired features and actually build the cache.
CacheLoader is an abstract class that specifies how to calculate or load values, if not present. There are two ways to create an instance of a CacheLoader:
1.        Extend the CacheLoader<K,V> class
2.        Use the static factory method CacheLoader.from
If you extend CacheLoader you need to override the V load(K key) method, instructing how to generate the value for a given key. Using the static CacheLoader.from method you build a CacheLoader either by supplying a Function or Supplier interface. When supplying a Function object, the Function is applied to the key to calculate or retrieve the results. Using a Supplier interface the value is obtained independent of the key.
The CacheBuilder is used to construct cache instances. It uses the fluent style of building and gives you the option of setting the following properties on the cache:
·        Cache Size limit (removals use a LRU algorithm)
·        Wrapping keys in WeakReferences (Strong references used by default for keys)
·        Wrapping values in either WeakReferences or SoftReferences (Strong references used by default)
·        Time to expire entires after last access
·        Time based expiration of entries after being written or updated
·        Setting a RemovalListener that can recieve events once an entry is removed from the cache
·        Concurrency Level of the cache (defaults to 4)
The concurrency level option is used to partition the table internally such that updates can occur without contention. The ideal setting would be the maximum number of threads that could potentially access the cache at one time. Here is an example of a possible usage scenario for Guava Cache.
The RemovalListener will receive notification of an item being removed from the cache. These notifications could be from manual invalidations or from a automatic one due to time expiration or garbage collection. The RemovalListener<K,V> parameters can be set to listen for specific type. To receive notifications for any key or value set them to use Object. It should be noted here that a RemovalListener will receive a RemovalNotification<K,V> object that implements the Map.Entry interface. The key or value could be null if either has already been garbage collected. Also the key and value object will be strong references, regardless of the type of references used by the cache.
There is also a very useful class CacheStats that can be retrieved via a call to Cache.stats(). The CacheStats object can give insight into the effectiveness and performance of your cache by providing statistics such as:
·        hit count
·        miss count
·        total load time
·        total requests
CacheStats provides many other counts in addition to the ones listed above.
The Guava Cache presents some very compelling functionality. The decision to use a Guava Cache really comes down to the tradeoff between memory availability/usage versus increases in performance.
above presentation eference :

Other Reference :

Thursday, 28 June 2012

How is it possible to access the equals method using a interface reference

How is it possible to access the equals method using a interface reference  

interface Shape {
   void draw();
class Square  implements Shape {
   int length,bredth;
   Square (int length,int bredth) {
      this.length = length;
      this.bredth = bredth;
   public void draw(){
      System.out.println("Inside Circle ");
   public int getArea() {
      return length*bredth;  

class ShapeMain {
   public static void main(String arg[]){
      Square obj = new Square(5, 5);
      System.out.println(obj.getArea()); // Calling getArea method from Square object is very well possible
      Shape s1 = obj;
      //We know that  Calling getArea method from Shape reference will give a compile time
      //because getArea is not visible to Shape interface.
      Shape s2 = obj;
      //Now the Crux is here .How is it possible to  call the equals method from the Shape interface which is         not declared ? See below for the answer

By default All the public  methods in Object class will be declared in the interface  if such method is not already declared in the interface
Below is the snapshot from JLS Specification

Bad habits of Programmers

1. Not learning anything new
Software development is a very specific industry branch. Unlike many other fields the speed of technology rotation is very high. New programming languages and frameworks are coming all the time. Current tools get upgraded to newer versions. By the time any serious book gets published on some technology v.1. and you've finished reading it, the v.2 has just been released. Not only the tools but programming methodologies and design techniques evolve as well. Usually they embrace the latest community knowledge and understanding of how to make things better. It is an obligation of every good programmer to keep oneself aware of the latest trends and achievements of the industry to continue perform on the highest level. If a programmer ignores the outside trends it is but a matter of time when his knowledge gets deprecated and his work quality falls below the current state of the art. When that happens he becomes obsolete in the new order. Learning new should be embraced with open arms. It should provide a continuous source of enjoyment and not seen as a punishment. If a programmer doesn't like learning new and doesn't enjoy the process he's probably missed the whole point of being a programmer.

2. Not seeking to extend your skills
Not only should a programmer stay current with the technology, he should also expand his knowledge horizons. There is hardly any good reason for a database guru to ignore everything about programming, or for an application programmer to stay away from any interface design. Interface designer could learn something about copywriting. A web programmer should learn about web security and search engine optimization. Not only is it extremely boring to focus on one narrow field, it is technically insufficient to produce great software. In order to develop your part to your best, you need to understand the other layers and components of a product. When you see the big picture, you see more options to accomplish your task and make it more efficient. Besides, the specialist work is clearly fading away into the past. With the technologies and tools getting more high-level and more powerful, a single programmer can perform several roles and develop an entire product single-handed. The demand for multi-skilled programmers is getting higher while specialists are finding themselves more often out of work. Looking into the other expertise fields is no different from learning new stuff. If you get curious about the new framework version, aren't you getting curious about copywriting, for example? A curious mind will readily peep into the other fields, a stalled mind will stay in the box and miss an opportunity to become better.

3. Not being open for new, sticking to old habits
Old habits are very difficult to change that's true. The same holds for software development practices. Once you've learned some way to deal with a programming problem, you keep to it for eternity. This is not necessarily bad provided you're looking up to new ways of doing the job and considering their suitability with an open-mind. Not any new idea is a good idea that's correct. But it is an attempt and experiment that matter. If however you reject any new ideas because you're unwilling to learn or simply because you've invested much time in your old method, then you're not doing well. A good programmer should always stay open to improvement suggestions and analyze them with no prejudgment. What if this new approach can make your work more efficient, more rapid, less error-prone? What if it points you to an idea of even a new approach that you could share with the community? A good programmer is always looking for ways to make his work better. Keeping a closed mind about any new developments leaves your little change to ever improve your work. And if you're thinking it is already good enough and cannot be made any better, then you need to rethink your involvement in software industry. There is no place for conservatism in here, the desire for experiment and innovation is what is driving it high into the sky.

4. Not caring about the quality of your work
Developing software is in many ways a creative activity. And similar to other creative professions the signature of a programmer in his work is very prominent. Like any other master, a programmer associates himself with the work he's doing. Hence comes the strive for work quality, in the code, in the architecture, in the innovative algorithms. It is a sign of a good programmer to attempt to perform his work with a high quality. In fact, with good programmers the quality issue comes very often in daily work. Good programmers just can't stand doing their job badly or contributing to a badly developed project. They want to redesign and refactor everything to bring it to that level of quality they can tolerate. Only then they're willing to proceed with the new work. As bad as it may look to an outside observer, it is actually a sign of a good programmer. If a programmer does not care about the quality of what he's doing, there's good chance you've met a fake programmer. Well, the one who doesn't like programming but only doing it as a job. Often such people leave a mess of the things because they can't tell mess from order or just don't care. Needless to say, you're not getting a great contributor with them.
5. Not seeking to improve the quality of your work
This is only a natural companion to the quest for quality. Again, in other creative activities masters are always seeking to become better, to experiment with their tools, with their medium, to try out new and unorthodox ideas while seeking their fulfillment. Good programmers are always trying to get better than they were yesterday. Hence comes a known "professional illness" – perfectionism. A programmer just can't stop refactoring the project again and again to fix little things and accommodate for bigger grand ideas on how to make the code and the architecture better. Missing deadlines and frustration from not achieving perfection are known symptoms. Even so, these are the character traits of a good programmer. Only through aiming at impossible can you actually grow. If you're not striving, you're not getting anywhere. And if you're standing still, you're never becoming a master.

6. Being a 9-to-5 worker with no passion
Working with passionate people is like nothing else. They're interesting personalities, curious about many things around programming, love experimenting with new ideas and can readily support your technical talk. It's that kind of person who can get inspired about an idea, drop everything and passionately pursue it days and nights until the project is done. Paired together with a passionate guy you can accomplish grand things. Passionate people are great contributors, they'll do things nobody thought of and perform many times more work than is expected of them.

On the other side of the fence, there are those "job" programmers who stay 9 to 5 and only do what their job duties prescribe. They rarely voice an opinion or fight about some programming issue, partially because they're not interested or don't care, partially because they're not smart enough. Contractors who'll do anything you ask for as long as the paycheck is good. Or your colleagues whom you never get to support any programming discussion during a lunch, they will talk about taxes, children and kindergarten, car problems or football but never touch anything programming-related. They don't experiment with the things on their own, never have any personal projects at home. They bore other passionate people and hardly contribute anything substantial. You can switch them any time for no significant loss.
Programming is more than just a job. You can only do it well if you love what you're doing. It's a prerequisite to becoming a good programmer and producing great stuff. If you don't love programming and only see it as a job, you'll never cross the threshold of mediocrity.

7. Not having own opinion of the things
One thing that you inevitably arrive at if you have interest and passion for you job, is to form an opinion of the tools you use. This programming language is not that good for the job, this one is better. This library has a bottleneck in this scenario, the other one has better performance. This architectural pattern may present certain scalability problems in the future, we choose another one and so on.
Opinion is very important. It's one thing that you base your choice on. And what big role a choice plays in programming, it's not up to me to tell you. Software development is all about choices. It is a very complex design activity where there is usually no prescribed process like in many engineering professions. A programmer is better seen as a designer. And as such he takes decisions all the time on every little element in the code. This is where opinion helps, it guides you through, helps to filter out the noise of random and sometimes wrong suggestions, ideas and information pieces and make the things right.
Opinion can only emerge if you care about what you do and have knowledge and experience to base your opinion on. And caring about your profession is essential to getting that knowledge and experience.
If you have no fire inside, no passion for the job, if nothing in what you do can ignite your spirit, if nothing programming-related can take you off on a new journey so that you drop everything and pursue your new interest, then it is clear you won't care much about programming stuff. Different languages, various libraries, old and new frameworks, architecture patterns and everything else, it's all the same, these are just the things that occupy your time 9 to 5 and cease to exist after you leave your office.
The problem is, if you don't care about programming, you don't really grow. You don't learn new technologies, you ignore what happens in that technology ecosystem, you don't look for opinions of other people, you don't experiment, you don't process the constant flow of information and knowledge, you don't participate in the development process. Ultimately, you don't learn much really. And if you don't learn, you don't grow as a professional. And that means you'll always be lacking a necessary component to form an opinion of the things.

One day it will surprise you that your new colleague 20 years younger than you can suddenly teach you a great deal about programming and has more competence than you. And somehow you're not taken seriously any more despite your 30 years of programming experience.

8. Accepting others' opinion without questioning
I know it sounds a little bit like being a rebel programmer, but this holds to be true. Whenever I see some solution, look at some decision or hear some opinion, I tend to analyze it critically and ask why this is so. Sometimes I agree, sometimes I don't. When I have an idea I propose a change or improvement to make things better. This has gotten me a few hot moments I admit, but I can't help myself. I've seen other programmers behaving the same way. Before accepting some way of doing things I want to know the reason it was done and has to be done this way, I look for an explanation. Because if I can't find an explanation or the guy responsible for that part can't explain why this is so, there is a good chance there is no real reason behind or the reason was deprecated long ago. Or maybe he just accepted this way of doing things from the guy before him who in his turn might have had no specific reason for this approach.
I think it is only natural for curious programming minds to attempt to look underneath, behind the scenes, to understand what is there and why it is there. We don' blindly accept that the wheel is rolling, we want to know how and why it is rolling. But I think it is a great trait. The curiosity has been the driving force in engineering and sciences for centuries and provided the humanity with many crucial discoveries. I can say about my programming practice that my curiosity has led me many times to spot some obscure bugs or discover hidden gems.

If a programmer blindly accepts everything as an absolute truth and takes everything for granted, then he either doesn't care about his work (which is bad), may not be a natural born programmer (even worse) or may just not be smart enough (probably the worst). So the next time your programmer asks you a tricky question, don't frown upon him and don't dismiss him as a misfit geek. Try to answer the question and you're likely to make a discovery for yourself.

9. Believing you've learnt it all
Any good programmer knows how bad he actually is. He understands it very well how little knowledge he has and what immense amount of information is still out there for him to grasp. This feeling encourages the continuous search for new knowledge and more experience in the glimpse of hope that tomorrow he will be a little bit less bad than he is today.

If anything can be said about the software world, is that the amount of information and knowledge in existence knows no limits. And it is vastly expanding every day just like our universe is expanding any second. For one thing that means that an individual can never learn it all no matter how hard he tries. But with a little bit of optimism you can see the other side, there is always some more knowledge to adopt to become better than you are now.
Programmers who understand this dilemma are in continuous learning process that expands their knowledge horizons. It's hard, challenging and time-consuming, but as a reward they become better with every day of their efforts.

On the other hand, programmers who think they know it all, or at least they know enough to perform their job and no more knowledge can help them do their job better, are on the losing side. They drop out of the programming universe which is expanding while they're staying behind. As a result, they're getting devalued as professionals and just become obsolete one day. And if they get surprised about this happening, this would only show they didn't understood the very basics of being a programmer.

10. Not tolerating any criticism
Among all other qualities of bad programmers, this one has always been the most destructive to the common working experience. It's intolerance to criticism, especially when constructive and justified.
Actually, it's not specifically a programmers' bad quality. It's just a bad human quality. I've seen it in other professions too. System administrators are notorious for their intolerant personalities. If you're carefully thinking about it, it tends to happen in professions where a person disposes of certain resources which are provided for other people to use. For example, system administrators manage a network of PCs which they might regard as their property which they rent. At least unconsciously, such transformation in their minds definitely happens. Naturally, if somebody questions their decisions, they get annoyed and respond in kind.
Programmers also have some kind of resources. It's their software that they build. They make a big investment with their knowledge, skills and passion into their work, which is later used by other people. In many senses, programming is a creative design activity, where a programmer associates himself with his work. It is only natural that any criticism is being accepted as a personal offence.

I think it is a bad quality. Criticism is very unpleasant, I concur. It's ego-based, it's human and you can't do anything about it. You can only learn to be a little bit more tolerant to it. To deny criticism altogether is not very smart, you can learn about you genuine mistakes and have an opportunity to correct them. Meaning, through sensible reaction to critics, you can become better in what you're doing.
Programmers who don't tolerate critics often have problems working in teams. They're in bad relationships with the other team members, they tend to isolate themselves from the team and ignore the external input and recommendations from their colleagues and superiors. This can result in that person being regarded as a foreign and disruptive element which only hinders the common efforts. Such people get removed from the team since a bad team player is useless no matter how technically proficient he might be.

11. Not listening to external input
Some programmers often tend to follow their own way. They write unneeded code, introduce elements into the architecture nobody asked for, redesign components and use their own decisions to guide them in their work. Often these decisions have nothing in common with what other people asked them to do. Usual response is "I think it is better this way, what you asked for was stupid and wrong".

Needless to say this behavior makes it very difficult to use these people in team work. Unless a programmer is coding some hobby project or has received a green light to take own decisions where he deems appropriate, he should listen and follow the input from others. There is quite often a room for discussion, if some request is really not that well-formed. Providing arguments, a programmer can persuade the other party of shortcomings of requested features and propose a better alternative.
By bluntly ignoring the input from other people, a programmer does not contribute anything to the work just delays it with the inevitably coming arguments about every "independent" decision. When the completed work is different from what was expected, we can talk about loss of time and resources because it has to be redone. In that case removing the programmer from the project might be a wise move.

12. Being ego-centric, know-it-all individual
Programmers like to take pride in their work. It is only natural and belongs to any other creative design activity. What is different about programming though, is that not every design is good and has absolute value for just being unique. There are always bad things to fix and good things to make even better. The wisdom to make things better often comes from other people, from their different knowledge and unique experience. Which is why it is absolutely necessary for a programmer to always stay open to accept any constructive and useful input from others.

In many cases it is not so easy however. The programmer's pride is so strong it cannot let for any external input or suggestion. The programmer thinks his opinion is the only one correct and his work is just perfect. Since he knows everything about the matter at hand, what could possibly somebody else contribute to the work? Right?

Unfortunately, it is a very wide spread case. Unfortunately indeed, because an overly big ego prevents a programmer from improving and perfecting his work, from achieving just the state he thought he was already at. This attitude is known to have blocked much useful input in practice and left the work with the issues unresolved.

In team work this personal position results in a tense working atmosphere, when a programmer is constantly protecting his (often bad) work and the other team members wasting their time fighting him to persuade him to take a second look at what he's been doing. This overly-developed ego actually makes a programmer unsuitable for team work and any other activity where communication with other people and external input are to be expected, like communicating with customers. Even if it were not the reason enough, just consider how much valuable input you are missing out by putting yourself above everyone else.

13. Having a negative personality and criticizing other people
Working with other people requires a certain level of communication skills and social tolerance. Many programmers have learned their skills on their own but as an unfortunate side effect turned into asocial geeks. Partially, the profession leaves its imprint. With programming we live in a binary world. Some function or an algorithm either works or it doesn't. Black or white, no gray scale. Probably this attitude got transferred to the working environment and the relationships with other programmers in the team. Either good work or bad work. A good programmer or a bad programmer. This sort of attitude destroys the friendly atmosphere in the team in a matter of days mostly weeks. I say it bluntly – there is no place for such an individual in the programming industry. He can't work in the team. He can't communicate politely with people on the web. He can't communicate with the customers and so on.

Once in my ancient job we got a new guy in the team to become the senior programmer and architect. The experience was daunting. The guy couldn't help but leave a picky comment at every opportunity. Leaving tragically formulated open phrases for which you don't usually find a positive answer. Seeing the screens of other programmers in the room display an error message once in a while (a normal work process) he used to nod his head and glance a look of remorse towards that person. Within first weeks the morale of the team dropped to the level of complete frustration. Needless to say, it didn't last long. The team leader noticed the problem and relocated the guy to work alone away from the team. From what I heard all attempts to teach him a few lessons of social behavior failed altogether. So he was asked to leave as soon as the project completed.

Doesn't matter what sort of guru you are, how strong your technical skills may be. If a programmer can't behave with respect to the others and hold on to the critics, he won't be welcome in any team. Remember your first days in programming. Sure you had to learn your skills by starting from scratch. You did some mistakes, small and big ones. Recall the people who patiently explained to you some complicated programming questions in the forums on the web. Recall your friendly colleagues who were gladly helping you when you needed help. Why don't you repay that old debt to your current colleagues with the same level of social consciousness?

The points above should sketch a portrait of a bad programmer as I've come to see it. In case you recognized yourself in some of them you know what to work on. Nobody is perfect at the start - everyone has to go a long way towards recognizing their shortcoming and agreeing to work on them. But until you've come to that point, you're not ready for the job.

Oracle - Types of Objects/Entities

Types of tables
  • Relational table
  • Object  table
  • Temporary table
  • Index organized table
  • Cluster
  • External table
  • XMLtype table
  • Partitioned table

Types of Constraints
  • Not Null
  • Unique (Why Unique key doesn't have index by default)
  • Check
  • Primary Key (Unique and Not Null)
  • Foreign Key
  • REF (Constrain -> New to me)

Types of Index
  • BTree (Balanced tree)
  • Bitmap
  • Function Based
  • Index Organized Table
  • Cluster
  • Bitmap Join
  • Domain

Types of Joins
  • Cross Join / Cartesian product
  • Natural (Find the same column in two table by default) / Inner Join
  • (USING (act_id)  | ON (a.act_id = b.act_id)
  • Outer Join
  • Left Outer Join
  • Right Outer Join
  • Full Outer Join
  • Self Join
  • Equi / Anti (Full table scan) / Range Join (use index but not good as equi)
  • Mutable (3 or more table join) / Complex Join  (also apply filters)

20 Subjects Every Software Engineer Should Know

Here are the most important subjects for software engineering, with brief explanations:

1.Object oriented analysis & design: For better maintainability, reusability and faster development,  the most well accepted approach, shortly OOAD and its SOLID principals are very important for software engineering.

2.Software quality factors: Software engineering depends on some very important quality factors. Understanding and applying them is crucial.

3.Data structures & algorithms: Basic data structures like array, list, stack, tree, map, set etc. and useful algorithms are vital for software development. Their logical structure should be known.

4Big-O notation: Big-O notation indicates the performance of an algorithm/code section. Understanding it is very important for comparing performances. 

5.UML notation: UML is the universal and complete language for software design & analysis. If there is lack of UML in a development process, it feels there is no engineering.

6.Software processes and metrics: Software enginnering is not a random process. It requires a high level of systematic and some numbers to monitor those techniques. So, processes and metrics are essential.

7.Design patterns: Design patterns are standard and most effective solutions for specific problems. If you don't want to reinvent the wheel, you should learn them.

8.Operating systems basics: Learning OS basics is very important because all applications runs on it. By learning it, we can have better vision, viewpoints and performance for our applications.

9.Computer organization basics: All applications including OS requires a hardware for physical interaction. So, learning computer organization basics is vital again for better vision, viewpoints and performance.

10.Network basics: Network is related with computer organization, OS and the whole information transfer process. In any case we will face it while software development. So, it is important to learn network basics.

11.Requirement analysis: Requirement analysis is the starting point and one of the most important parts of software engineering. Performing it correctly and practically needs experience but it is very essential.

12.Software testing: Testing is another important part of software engineering. Unit testing, its best practices and techniques like black box, white box, mocking, TDD, integration testing etc. are subjects which must be known.

13.Dependency management: Library (JAR, DLL etc.) management, and widely known tools (Maven, Ant,  Ivy etc.) are essential for large projects. Otherwise, antipatterns like Jar Hell are inevitable.

14.Continuous integration: Continuous integration brings easiness and automaticity for testing large modules, components and also performs auto-versioning. Its aim and tools (like Hudson etc.) should be known.

15.ORM (Object relational mapping): ORM and its widely known implementation Hibernate framework is an important technique for mapping objects into database tables. It reduces code length and maintenance time.

16.DI (Dependency Injection): DI or IoC (Inversion of Control) and its widely known implementation Spring framework makes life easy for object creation and lifetime management on big enterprise applications.

17.Version controlling systems: VCS tools (SVN, TFS, CVS etc.) are very important by saving so much time for collaborative works and versioning. Their logical viewpoint and standard cammands should be known. 

18.Internationalization (i18n): i18n by extracting strings into external files is the best way of supporting multiple languages in our applications. Its practices on different IDEs and technologies must be known.

19.Architectural patterns: Understanding architectural design patterns (like MVC, MVP, MVVM etc.) is essential for producing a maintainable, clean, extendable and testable source code.

20.Writing clean code: Working code is not enough, it must be readable and maintainable also. So, code formatting and readable code development techniques are needed to be known and applied.

Java 7 Features
vm JSR 292: Support for dynamically-typed languages (InvokeDynamic)
Strict class-file checking
lang JSR 334: Small language enhancements (Project Coin)
core Upgrade class-loader architecture
Method to close a URLClassLoader
Concurrency and collections updates (jsr166y)
i18n Unicode 6.0
Locale enhancement
Separate user locale and user-interface locale
ionet JSR 203: More new I/O APIs for the Java platform (NIO.2)
NIO.2 filesystem provider for zip/jar archives
SCTP (Stream Control Transmission Protocol)
SDP (Sockets Direct Protocol)
Use the Windows Vista IPv6 stack
TLS 1.2
sec Elliptic-curve cryptography (ECC)
jdbc JDBC 4.1
client XRender pipeline for Java 2D
Create new platform APIs for 6u10 graphics features
Nimbus look-and-feel for Swing
Swing JLayer component
Gervill sound synthesizer
web Update the XML stack
mgmt Enhanced MBeans

Wednesday, 27 June 2012

Java - Is is possible to access private values through reflection?

import java.lang.reflect.Field;

class A {
    private int i = 10;
    private int j = 10;
    A(int i,int j) {
    private static String ProtectData() {
        return "Protected Password";
    private static String SecureData() {
        return "Secure Password";

Non- Generic way of access the private variable

public class Test {

     * @param args
    public static void main(String[] args) throws Exception {
        Object cl = new A(20,36);
        java.lang.reflect.Method m = cl.getClass().getDeclaredMethod("ProtectData",null);
        java.lang.reflect.Field f = cl.getClass().getDeclaredField("i");
        f.setInt(cl, 45);
        String pass = (String) m.invoke(null, null);
        int passed = (int) f.getInt(cl);
        System.out.println("Protected data:" + pass);
        System.out.println("Protected data:" + passed);


Generic way of access the private variable
class Tests {

    public static void main(String[] args) throws Exception {
        Object cl = new A(20,36);
        java.lang.reflect.Method[] m = cl.getClass().getDeclaredMethods();
        java.lang.reflect.Field[] f = cl.getClass().getDeclaredFields();
        f[0].setInt(cl, 30);
        String pass = (String) m[1].invoke(null, null);
        int passed = (int) f[0].getInt(cl);
        System.out.println("secure data:" + pass);
        System.out.println("secure data:" + passed);


We protect our object form this Hacking Technique?
To call setAccessible when security is enabled, you must have the suppressAccessChecks permission. By default, code that is in the core API or the extensions directory will have the suppressAccessChecks permission and be able to perform services such as serializing an object's private state.
/* grant the klib library AllPermission */
grant codebase "file:${klib.home}/j2ee/home/klib.jar" {
  permission java.lang.reflect.ReflectPermission "suppressAccessChecks";


Just spend you precious minute to analysis the following code and predict the output
public class Puzzle {
    public static void main(String[] args) throws Exception {
      String String;
      String = new String("Welcome to our Puzzle");
      System.out.println("String "+String);


Representational State Transfer (REST) has gained widespread acceptance across the Web as a simpler alternative to SOAP- and Web Services Description Language (WSDL)-based Web services.
Key evidence of this shift in interface design is the adoption of REST by mainstream Web 2.0 service providers—including Yahoo, Google, and Facebook—who have deprecated or passed on SOAP and WSDL-based interfaces in favor of an easier-to-use, resource-oriented model to expose their services
            REST has emerged in the last few years alone as a predominant Web service design model.
REST web services have won the hearts of many working developers. For example, Amazon's web services have both SOAP and REST interfaces, and 85% of the usage is on the REST interface. Compared with other styles of web services, REST is easy to implement and has many highly desirable architectural properties: scalability, performance, security, reliability, and extensibility.

Oracle : Very good document about explain plan (a must to read)!

Oracle : Number of fractional digit(s) for a number

Here is the way:

SELECT cashAmnt,  length(MOD(abs(cashAmnt),1))-1 FROM sales;

Works on negative numbers also

Oracle - Temporary Table

Core part of Temporary Table

Ø        Data only visible from the current session

Added Advantages

Ø        Index can be created on temporary table
Ø        Check constraints is possible  (unicity, limited set of possible values…)
Ø        A view can reference a temporary table
Ø        No FOREIGN KEY, no storage allocation, no INITIAL extent, no tablespace
Ø        Temporary table allocates storage from the temporary tablespace of the connected user.

Why Temporary table is faster

Ø        Temporary tables generate no redo logs for their blocks.

What need to be avoided while using Temporary table.

Ø        Temporary tables generate undo, and the undo is logged.
Ø        So we must avoid deleting or updating from temporary tables. You can just let the temporary tables empty themselves automatically after a commit.
Ø        If billions of rows will be inserted producing a temporary tablespaces full, If such a process does not give performance increase

What should we do using Temporary table

Ø        You should use temporary tables mostly for inserting or selecting of data

Java : Constructors must not invoke overridable methods

public class Override_Test {
   public static void main(String... args) {
      new Maruthi();

class Car {
   String sName;

   Car() {
      sName = "Car Cycle";

   public void print() {
      System.out.println("CAR : " + sName);

class Maruthi extends Car {
   String sModel = "900";

   Maruthi() {
      sModel = "800";

   public void print() {
      System.out.println("MARUTHI : " + sModel);

Let we guess the output of this implementation…

In Car constructor we are calling an overridden method print…

Moral : Constructors must not invoke overridable methods

Output :   MARUTHI : null

JEE Web Services 5 Jargons

JEE Web Services 5 Jargons
JSON JavaScript Object Notation
JAX-WS Java API for XML-based Web Services
StAX Streaming API for XML
REST Representational state transfer
JAXB Java Architecture for XML Binding
WSIT Web Services Interoperability Technologies
WCF Windows Communication Foundation
SOA Service Oriented Architecture
BPEL Business Process Execution Language

Software As A Service (SaaS)

SaaS is a new model of how software is delivered. SaaS refers to software that is accessed via a web browser and is paid on a subscription basis (monthly or yearly). Different from the traditional model where a customer buys a license to software and assumes ownership for its maintenance and installation, SaaS presents significant advantages to the customer.

SaaS is faster and a cost effective way to getting implemented. There are no hardware, implementation or acquisition costs involved to run the application from the customer's side. It's the responsibility of the SaaS vendor (us) to manage and run the application with utmost security, performance and reliability.

Since customers pay a subscription, they have immediate access to the new features and functionality. Unlike traditional softwares where upgrades would happen once a year or once in 6 months (with the vendor coming to your office with a CD), the SaaS vendor continuously pushes new updates, fixes to the application, which is immediately accessible by the customer. This reduces the length of time it takes a customer to recognize value from the software.

Since the software application is delivered as a service, its important for the vendor to focus on customer service and experience. Since this is on a subscription model, the vendor is judged on a month-month basis and the pressure to innovate or risk losing business is greater.

SaaS can be used by Windows, Linux, or Mac users, providing true platform independence over the Internet.

{Synchronization} Object and Class level lock

package com.test;

public class TestThreadLock {

   public static void main(String... strings) {
      TestThread t = new TestThread();
      Thread t1 = new Thread(t);
      Thread t2 = new Thread(t);


class TestThread implements Runnable {

   public void run() {

   public void fun1() {

   public synchronized void fun2() {

   public void fun3() {
      synchronized (this) {

   public static void fun4() {

   public static synchronized void fun5() {

   public void fun6() {
      synchronized (TestThread.class) {


Choosing Hibernate Cache Provider

Choosing a cache provider
For now, Hibernate forces you to choose a single cache provider for the whole application. Providers for the following products are built into Hibernate:
EHCache is intended for a simple process scope cache in a single JVM. It can cache in memory or on disk, and it supports the optional Hibernate query result cache.
OpenSymphony OSCache is a library that supports caching to memory and disk in a single JVM, with a rich set of expiration policies and query cache support.
SwarmCache is a cluster cache based on JGroups. It uses clustered invalidation but doesn’t support the Hibernate query cache.
JBossCache is a fully transactional replicated clustered cache also based on the JGroups multicast library. The Hibernate query cache is supported, assuming that clocks are synchronized in the cluster. It’s easy to write an adaptor for other products by implementing net.sf.hibernate.cache.CacheProvider.
Not every cache provider is compatible with every concurrency strategy. The
compatibility matrix in table will help you choose an appropriate combination.
Cache concurrency strategy support
Cache Provider read-only
Non strict read-write read-write transactional
EHCache X X X  
OSCache X X X  
SwarmCache X X    
JBossCache X     X