Disclaimer

I have been playing around with MongoDb, thanks to the M101J Course offered by Mongodb University. These NoSQL datastores are gaining popularity due to a number of reasons and one among them being the ease with which they can be scaled out i.e horizontal scaling. This horizontal scaling in MongoDB can be achieved by creating a sharded cluster of mongodb instances.

We all have read in Java books about encapsulation of fields in Java class and also when ever you code you are asked to take special care in encapsulating the fields and providing explicit Getters and Setters. And these are very strict instructions. Lets step back a bit and find out the reason behind encapsulating the fields. Its all done to have a control over the access and modification of the fields. One might want to allow the user of the class to access data from only few fields or control the update of data of the fields in the class and so on. And on other occassions the frameworks would need these getters and setters to populate your POJOs(Plain Old Java Objects).

Now the pain involved in adding these getters and setters is quite a bit and this pain has been reduced by the IDEs which allow you to generate the getters and setters for the fields. But these generated code make your class definition very verbose and hide the actual business logic, if any, which you might have it inside the class definition. There have been lot of ways by which you can get away with defining the getters and setters explicitly and I have even blogged about using Project Lombok to use annotations to declare the getters and setters. I have come across another approach to avoid defining the getters and setters and this approach doesn’t even auto generate the code or use annotations to define them. I am sure I have read this approach somewhere but unable to recall, so its something which has been used and I am trying to create an awareness among my readers about this approach via this blog post.

Let me first define the class with the getters and setters and then show how to get rid of them

There is nothing to explain in the above code, pretty clear with fields being private and public getters and setters. The class definition is about 60 lines. Let see how we can define class without providing getters and setters:

The above is what I call class definition on diet It is less verbose and is just 18 lines. You must be scared looking at the public modifiers for the fields and also confused looking at the final modifiers to the field. Let me explain the ideology behind this approach:

As the fields are final they cannot be modified after initialized so we need not worry about the scare of data in the field getting modified. And we have to provide a constructor which will initialize these fields, otherwise compiler will shout at you for not understanding what final modifier is.

The data in the fields can be accessed by using the fields directly and not via the getter methods.

This approach enforces immutability of objects i.e if we have to update the field we have to create a new object with the updated value of the field.

Now having Immutable objects provides lots of advantages few of them being:

Writing concurrent code is quite easy because we need not worry about getting locks on the object as we are never going to modify the object, we can just read the object data and cannot modify due to the use of final.

Immutable objects leads to having lot of short lived objects which helps in reducing the GC overhead involved in managing long lived objects and objects with lot of live references.

We can even provide a factory method for creating instances of Task. Lets see the above class in action:

Update:
Thanks a lot for the comments and your thoughts both here and on DZone. I spent some time in identifying how one can work without the need for getters and setters in scenarios mentioned where without getters and setters its not possible. One such scenario is marsalling and unmarshalling of JSON and another scenario is where we have a List of some values as property and we need to give an read only access to the users of the object. The below are examples of using POJOs without getters and setters in JSON marshalling and unmarshalling using GSON and Jackson JSON libraries:

Lot of times we would have to fetch the data from a database or another webservice or load it from file system. In cases where it involves a network call there would be inherent network latencies, network bandwidth limitations. One of the approaches to overcome this is to have a cache local to the application.

If your application spans across multiple nodes then the cache will be local to each node causing inherent data inconsistency. This data inconsistency can be traded off for better throughput and lower latencies. But sometimes if the data inconsistency makes a significant difference then one can reduce the ttl (time to live) for the cache object thereby reducing the duration for which the data inconsistency can occur.

Among a number of approaches of implementing local cache, one which I have used in a high load environment is Guava cache. We used guava cache to serve 80,000+ requests per second. And the 90th percentile of the latencies were ~5ms. This helped us scale with the limited network bandwidth requirements.

In this post I will show how one can add a layer of Guava cache in order to avoid frequent network calls. For this I have picked a very simple example of fetching details of a book given its ISBN using the Google Books API.

A very detailed explanation on the features of Guava Cache can be found here. In this example I would be using a LoadingCache. The LoadingCache takes in a block of code which it uses to load the data into the cache for missing key. So when you do a get on cache with an non existent key, the LoadingCache will fetch the data using the CacheLoader and set it in cache and return it to the caller.

Lets now look at the model classes we would need for representing the book details:

Lets now define a service which will fetch the data from the Google Books REST API and call it as BookService. This service does the following:

Fetch the HTTP Response from the REST API.

Using Jackson’s ObjectMapper to parse the JSON into a Map.

Fetch relevant information from the Map obtained in step-2.

I have extracted out few operations from the BookService into an Util class namely:

Reading the application.properties file which contains the Google Books API Key (I haven’t committed this file to git repository. But one can add this file in their src/main/resources folder and name that file as application.properties and the Util API will be able to read it for you)

We can create a cache object using the CacheBuilder API provided by Guava library. It provides methods to set properties like

maximum items in cache,

time to live of the cache object based on its last write time or last access time,

ttl for refreshing the cache object,

recording stats on the cache like how many hits, misses, loading time and

providing a loader code to fetch the data in case of cache miss or cache refresh.

So what we would ideally want is that a cache miss should invoke our API written above i.e getBookDetailsFromGoogleBooks. And we would want to store maximum of 1000 items and expire the items after 24 hours. So the piece of code which builds the cache looks like:

Its important to note that the maximum items which you want to store in the cache impact the heap used by your application. So you have to carefully decide this value depending on the size of each object you are going to cache and the maximum heap memory allocated to your application.

Lets put this into action and also see how the cache stats report the stats:

{"isbn13":"9780596009205","authors":[{"name":"Kathy Sierra"},{"name":"Bert Bates"}],"publisher":"\"O'Reilly Media, Inc.\"","title":"Head First Java","summary":"An interactive guide to the fundamentals of the Java programming language utilizes icons, cartoons, and numerous other visual aids to introduce the features and functions of Java and to teach the principles of designing and writing Java programs.","pageCount":688,"publishedDate":"2005-02-09"}
CacheStats{hitCount=4, missCount=1, loadSuccessCount=1, loadExceptionCount=0, totalLoadTime=3744128770, evictionCount=0}

This is a very basic usage of Guava cache and I wrote it as I was learning to use this. In this I have made use of other Guava APIs like Optional which helps in wrapping around existent or non-existent(null) values into objects. This code is available on git hub- https://github.com/sanaulla123/Guava-Cache-Demo. There will be concerns such as how it handles concurrency which I havent gone detail into. But under the hood it uses a segmented Concurrent hash map such that the gets are always non-blocking, but the number of concurrent writes would be decided by the number of segments.

ConEmu (http://www.fosshub.com/ConEmu.html) is a very useful and much much better Console window for Windows. It acts as a facade over the cmd.exe. There are loads of good things in it and highly recommended for programmers who are windows users.

If you have installed Cygwin, you can integrate bash with your ComEmu terminal so that you can open a new tab running your bash shell :). On similar lines you can open new tabs running Git shell if you have installed git-shell.

To integrate Cygwin bash –
1. Open the setting – Windows + Alt + P
2. Select Startup -> Tasks
3. Click on “+” to add a new task
4. Name it as “Cygwin bash” or “cygwin” which ever is comfortable.
5. In the commands text area paste this: “%SystemDrive%\cygwin64\bin\bash.exe” –login -i
6. Save and exit the settings.

Murach’s Java Servlets and JSP is the ONLY book you need to learn Web App Development in Java using JSP and Servlets. The book covers all the concepts required you to build a complete Web application in Java. You will find topics covering:
– UI Development using HTML, Javascript
– Building Servlets for handling requests.
– Using JSP to create UI templates
– Building Data access layer to communicate with DB.

Its a completely hands on guide and just mere reading will be of no help. The book also covers concepts and techniques related to secure programming and also some advanced concepts in servlets.

Few among numerous salient features:
Completely hands on guide
Highly suitable for people who are familiar with Java language
Focuses on best practices where ever relevant. For example in the chapters which explains about JSP there is a guideline not to mix java code with JSP and instead make use of JSP Template Library.
Lot of reusable code snippets – useful if someone is looking to implement a subset of the feature explained.

I would highly recommend this book to –
“Any developer familiar with Java programming language looking to learn Web application development using Servlets and JSP”.

One can purchase the latest edition here [though currently only imported edition is available].

The author covers most of the features of dropwizard which includes creating RESTful End points, Database access, Authentication, Creating views by means of developing a sample Phonebook application.

The book is not an exhaustive guide to dropwizard and may not match the documentation provided on the Dropwizard official site. But the approach of developing a sample application adding features in each chapter might appeal to some readers.

If you are kind of person who likes learning a framework by developing a sample application, then you can pick this book. Otherwise I would suggest the documentation would suffice.

I have been working on integrating with RabbitMQ to implement the messaging architecture. All the time I made use of the basic tutorials available on RabbitMQ site to wade through understanding different concepts around AMQP and RabbitMQ.

It picks a fictitious company and its requirements to develop a messaging feature. The author builds up the features very elegantly.

Author explicitly focuses on good practices, performance in the examples presented in the book

Also touches upon how messaging architecture can integrate heterogenous software systems with software pieces written in Ruby, Python, Java.

Liberal use of diagrams to explain the architecture and flow of messages

I already had familiarity with communication constructs of RabbitMQ and didn’t find it difficult to understand the content and intent of the author. It also helped me to understand few intricate aspects like Dead letter queue and how to handle them, handling mandatory messages, setting ttl on the messages, different exchange types like direct, topic and fanout.

I feel the book is good read for anyone who has started using RabbitMQ and has worked on integrating with the client API. This book will help you correct your implementation and also understand few gotchas which one would encounter in real life projects.

So we have been able to test for 2 inputs, imagine extending the above for more number of inputs? Unnecessary bloat up in the test code.

JUnit provides a different Runner called Parameterized runner which exposes a static method annotated with @Parameters. This method has to be implemented to return the inputs and expected output collection which will be used to run the test defined in the class. Lets look at the code which does this:

We write service APIs which cater to certain business logic. There are few cross-cutting concerns that cover all service APIs like Security, Logging, Auditing, Measuring Latencies and so on. This is a repetitive non-business code which can be reused among other methods. One way to reuse is to move these repetitive code into its own methods and invoke them in the service APIs somethings like:

The above approach will work but not without creating code noise, mixing cross-cutting concerns with the business logic. There is another approach to solve the above requirements which is by using Aspect and this approach is called Aspect Oriented Programming (AOP). There are a different ways you can make use of AOP – by using Spring AOP, JavaEE AOP. In this example I Will try to use AOP using CDI in Java EE applications. To explain this I have picked a very simple example of building a web application to fetch few records from Database and display in the browser.

@AroundInvoke designates the method as an interceptor method. An Interceptor class can have only ONE method annotated with this annotation. When ever a target method is intercepted, its context is passed to the interceptor. Using the InvocationContext one can get the method details, the parameters passed to the method.

We need to declare the above Interceptor in the WEB-INF/beans.xml file

We have annotated the service methods with the Interceptor binding @LatencyLogger. The other way would be to annotate at the class level which would then apply the annotation to all the methods of the class. Another thing to notice is the @Inject annotation that injects the instance i.e injects the dependency into the class.

Next is to wire up the Controller and View to show the data. The controller is the servlet and view is a plain JSP using JSTL tags.

The above servlet is available at http://localhost:8080//AOPDemo. It fetches the data and redirects to the view to display the same. Note that the Service has also been injected using @Inject annotation. If the dependencies are not injected and instead created using new then the Interceptors will not work. This is an important point which I realised while building this sample.

With this you would have built a very simple app using Interceptors. Thanks for reading and staying with me till this end. Please share your queries/feedback as comments. And also share this article among your friends

If you want to:
– learn about commands used for OS monitoring
– understand about different components of JVM
– monitor and tune JVM to improve its performance.

then, Java Performance is the book you should be picking. This book covers :
– command line tools for OS monitoring.
– JVM overview.
– tools used for monitoring Java applications.
– tuning JVM where majority of it related to GC tuning.
– tuning Java EE applications.

The book has 12 Chapters and not all chapters are required to be read in one go. Its recommended to read all the chapters until chapter 7 as they cover some really interesting and important topics relevant to OS monitoring, JVM basics, JVM monitoring, JVM tuning.

The chapters covering Web Services performance rely on SOAP based services and might not be really relevant to few readers. Also Glassfish is used as the app server for examples in Java EE related monitoring chapters. These few chapters (chapters 8-12) can be read as and when the need arises.

Though the book has been published in 2011, it covers the latest GC algorithm – G1 Algorithm and also calls out any changes/optimisations that can be done in Java 7. So one cannot rule out this book as outdated.

I really benefitted from this book- the chapters related to OS monitoring, JVM overview, JVM monitoring, JVM tuning are the best, resourceful and highly informative. Also the step-by-step approach to JVM tuning described in the book helps a lot in tuning your Java applications.

Anyone reading this book should have good understanding of Java programming and also have at his disposal a Java application which they can tune as they read through the chapters. Mere reading will not be helpful.