Extending Java API with Lombok Annotation Preprocessor

Annotations can also be used in a bit unusual way to modify the existing code base at compile time. Generally, additional methods are generated by so-called Annotation Processor which uses annotations to provide additional API. One of the most famous tools which behaves in this way is Lombok...

Fewer Bugs With Annotations In Java

Another purpose of annotations is code protection at compilation time. @Override annotation is the best candidate to describe what it means. This annotation is used to notify the compiler that the method is overridden deliberately. It stresses that the method is exactly overridden but not overloaded. Hence, all its parameters and return type match the method of parent class...

Keep Sorting Clean and Obvious in Java

Imagine you have got a task to sort pet array/list by name in alphabetical order. If names of two pets are identical then their ages should be compared. Later, a weight property steps in. If no discrepancies found until now, the owners are compared in the following way. If their ages are the same then their names are compared in reverse alphabetical order. Have you ever got a task to implement sorting algorithm in which at least three object properties are involved...

Annotation Driven Development in Java

Java gives developers a powerful tool that can extend an application functionality drastically and make a code much easier to read. This tool is called Annotations. Since they appeared in Java, many frameworks have changed their behaviour on how to provide their API to user. This new annotation-driven approach makes usage of the most popular frameworks much easier. So, in my opinion, knowing how to use annotations is 'must have' for every Java developer...

The Power of Annotations in Java

General-purpose annotations have emerged in Java since 1.5 release in 2004. Since then, they play one of the most vital part in the life cycle of many well-known frameworks, such as Spring Framework, Hibernate, etc. Some libraries went further and add ability to extend the language itself using annotation (yes, I mean tools like Lombok...

How to parse date in Java 5, 6 and 7 using Joda Time

Time has been the most controversial and changeable topic since Java has introduced in 1995. Three different approaches were created to make time formatting as easy as possible since then. First approach was introduced together with Java in 1995. And... become obsolete almost immediately. Second approach has appeared in 1997 but the operations with time were still difficult to use in Java code. The light at the end of the tunnel has appeared with the emerging of Joda Time library in the mid of 2000's...

How to parse date in Java 5, 6 and 7 using Java API

In our previous topic we were talking about formatting data in Java 5-7. Today we will talk how to convert some string representing date into Date object using only Java API. Basically, you will not need to do it often because there is Joda-Time library which makes process of parsing date much easier. But anyway if you are a Java software engineer you have to know how to parse date in older versions of Java...

How to format date in Java 5, 6 and 7 using Java API

I assume no one Java API has been evolved so much as Date API. The story was started with Date class which is one of the oldest Java core classes and it was added to the very first version of Java. But soon it became clear that it is difficult to use this class and Calendar has been introduced one year later in Java 1.1. Since then the creation of date became much easier but formatting date was still a boring process. No wonder that Java 1.2 brought the class called SimpleDateFormat to fill this niche. Later Joda Time library enhanced date API a lot and it was a standard for creation, formatting and parsing date in Java until Java 8 released in 2014...

Override toString() method correctly in Java

Every object in Java inherits several methods from its ancestor Object class. They are clone(), equals(), finalize(), getClass(), hashCode() and toString(). Let's talk about the last one toString() method. Its implementation in Object class merely returns object's class name and hex representation of result of hashCode() method. It, in turn, uses Park-Miller random number generator algorithm to generate object's hash code...

Seven rules of ExecutorService usage in Java. Rule #7. Create a service to manage thread pools

This article will merge all approaches covered in all previous chapters. Actually, a project on GitHub was created to cover all this stuff. So, you can download this project and enjoy using it. With the help of ThreadPoolService (it's a name of this project) you can: name a thread in ExecutorService, handle exceptions thrown by any task submitted to ExecutorService, get the statistics of usage of the thread pool, shutdown all thread pools in the single-exit point etc...

Seven rules of ExecutorService usage in Java. Rule #6. Use different thread pools for CPU intensive, IO and blocking tasks

This is the sixth rule but it is one of the most important rules. It can be easily explained using the following example. Imagine there are 9 tasks. 6 low-priority tasks that fetch data from a very slow remote resource. Basically, it takes 30 seconds to complete any of them. Three high-priority tasks just checks user credentials very quickly but every user has to wait for credential response. Also, there is a thread pool with 3 threads in there. Let's assume the first 6 tasks are scheduled in the execution queue and 3 credential tasks go just after them. Hence, 3 users will wait for 1 minutes before they get credentials response. Explanation? There are 3 threads and 6 tasks. So, every thread will execute 2 tasks. The execution time of every task is 30 seconds. Therefore, the execution of 2 tasks requires 1 minute. Obviously, 1 minute is a huge delay and I'm sure that nobody wants to wait so long...

Seven rules of ExecutorService usage in Java. Rule #5. Keep an eye on your ExecutorService utilization

Assume that you have already created a thread pool using ExecutorService and this pool has started doing its job. Is it possible that there is no enough work for the thread pool and the most threads do nothing? Yes, that's highly possible. Is it possible that there are too many tasks and the thread pool can not execute them on time? Yes, this is also possible. Also, fixing both of these situations is extremely easy. In first case, you have to reduce the number of threads in the thread pool. In the second case, increasing thread number will probably solve the issue. But how can we detect these situations? Basically, monitoring of every thread pool is required...

Seven rules of ExecutorService usage in Java. Rule #4. Stop using Thread.sleep() method but use ScheduledExecutorService instead

Thread.sleep() method is considered as the simplest well-known way to wait before a single action or delay between repeated actions. But in the most cases it can be avoided using ScheduledExecutorService. What's more, using Thread.sleep() in ExecutorService may cause a situation in which some threads are keeping execution context and disallow other threads to do anything. Let's look at the following example that depicts this situation...

Seven rules of ExecutorService usage in Java. Rule #3: Name the threads of a thread pool

Actually, you have to name every thread you create. No matter how you create them: using ExecutorService, Thread class or some other way. If your threads are named then you can much easily identify the cause of a problem and debug more efficiently. Otherwise, you'll see logging messages containing thread names like Thread-1 or something like that. By the way, useless information at all. The same situation happens during profiling and debugging an application. A lot of threads and each of them are named Thread-1, Thread-2, Thread-3 and so on...

Seven rules of ExecutorService usage in Java. Rule #2: Handle Exception in every ExecutorService's task

Let's continue talking about ExecutorService usage but, first, I want to say a few words about logging messages. Pay attention the code below contains a lot of statements that print to the standard out (System.out.print). In the real live all of them should be replaced with the call to Logger's method. Do not use System.out.println under any circumstances in production environment! Or your colleagues will create a voodoo doll. Because every modern Logger allows you to write log messages not only to standard out but also to an arbitrary location of your hard drive or even cloud. And this flexibility is the reason why you should use Logger...

The Seven rules of ExecutorService usage in Java. Rule #1: Don't forget to call shutdown method

Despite the fact that java.util.concurrent package was added to Java standard edition in 2004, a huge number of software developers still use concurrent package incorrectly or do not use it at all. Some developers continue managing their threads with the help of Thread class, popular approach before Java 5.0, and they try to avoid modern concurrent package at all costs. Basically, this behavior is logical. Thread gives a user the total control, its behaviour is extremely simple and easy to understand. At the same time, ExecutorService, the descendant of Thread, hides the thread internals from the user. Obviously, it generates additional barrier to understand it correctly...

How to handle uncaught exception in Java?

Sometimes exceptions happen. No matter how cool your application is and no matter how much time you spent creating the perfect architecture. You know that every software engineer writes clean code and creates perfect components but there is army of bad guys somewhere in the Universe that create tons of bad code and commit it to Earth’s repositories. No one understands how this is happening… but… Anyway, you need some mechanism to catch all exceptions in your application. And this mechanism exists...

Switch between different synchronization mechanisms in Java 8

I guess most Java developers are aware that a block of code can be synchronized using synchronized block of Lock object. For instance...

Bash script that builds Gradle web project and deploys it to local Tomcat

Imagine that you develop a web application that should be tested on real Tomcat instance or on several instances simultaneously. In this case every time you build your project you have to copy and paste it to Tomcat webapp directory, do some clean work and, probably, restart web-server. Of course, this tedious work may be automated. Here you can find a bash script that builds a web project, cleans Tomcat folders, copies war file to Tomcatâ??s webapp dir and starts Tomcat...

How to use dropWhile and takeWhile in Java 8

Java 8 has provided us with a lot of nice features that make life of a software developer much easier. But this article is not about new features of Java 8. This article is about only a small piece of a new Stream API. Let’s assume that we have a list containing persons sorted by their balance on a bank account. We need to skip all Persons which bank’s account has less than $1000 and take only 5 persons whose names start with ‘t’ letter. How to do it in Java 7? It’s quite easy...

How to Prevent Deadlocks in Java

Deadlock may be a very huge headache for every software developer. Usually due to the fact that they are difficult to detect. For instance, some specific application may work without any problems within several weeks or even months. But then, unexpectedly, it becomes unusable and the very first thing is done in this situation is an application restart. In fact, it is the worst decision in this case because the state of the threads will be lost forever and the developer will never know what happened and how to fix it fast. The first action a software developer has to do in this case is creation of threads dump to depict the problem in detail. On the other hand, I believe that it is better to prevent a problem than to fix it later. So, how to prevent deadlocks in Java...

How to detect process id of Java application

The detection of the process id is the first thing the developer should do in an effort to diagnose their application. Due to the fact that most Java applications are run under Unix environment, let’s start with the detection procedure in these kind of systems...

How to Fix Deadlocks in Java

First of all, what is a deadlock? The deadlock is the state of an application in which it can not handle or process some data because some of its threads are stuck and waiting for the lock kept by another threads...