Happens-Before In Java Or How To Write a Thread-Safe Application

Multithreading is the most complex part of Java. Happens-before is a relation that gives a guarantee of allowing the writing of predictable code in multithreading a reality. Such code is also known as thread-safe code. Unfortunately, Oracle Java documentation about this notion is hard to read. So in this article, I'll mainly explain what happens-before is in human language and provide detailed examples.

Happens-Before Solves the Main Multithreading Problem

Before we start learning the happens-before notion, we have to understand the reason for creating it. Once multithreading comes to the scene, your code might become inconsistent because shared objects between threads might have different and unpredictable values. Let's review a simple example. In that example, we will update values in one thread and read and print them in another.

Writing Indexes in Java by Using Right Collection

What Index Is and How To Use It in Java

An Index is a structure that facilitates search in your data. Is a pretty general term and doesn't belong to some language or database. In order to explain it let's create a way to search users for specific criteria like name, id, birth date, etc.

Quickly Searching Among Millions of User Entries

Let's assume that we have 1 million users. As a requirement, we have to expose API to search users by specific criteria. Obviously, simple iteration will take too much time. So let's sort this problem using indexes (or simply saying by pre-generating some data that accelerate lookup during API calls). So first place let's define our User class and Search interface:

Saving Memory In Java: Making The Smallest Memory Footprint

Articles To Read Before We Start

I've already written articles about memory estimation. The first one explains how to calculate memory for objects, arrays, etc. The second one shows tools for how to estimate recursively any object size. Before you begin this article, I strongly recommend you read the first ones. Otherwise, it would be a bit difficult to understand how I calculate the size of objects.

This article will cover the next tricks and topics:

Don’t Underestimate Documentation

Documentation Sounds Like an Annoying, Boring Thing

Maybe you feel that documenting the project or your code is an extra annoying step. Often, documentation for projects is outdated and irrelevant. In such cases, most of the expertise is hidden in analysts or just developers. In this article I'll try to explain why having a good documentation culture will make projects much more stable and successful.

Writing Good Documentation Often Makes a Big Difference

There is no specific rule on how to make perfect documentation, but obviously plain text without details is much worse than documentation with screenshots, diagrams, and images. It takes time to write a quality manual, but it's worth it because it solves many problems at once, including slow onboarding processes, slow communication, single-person projects, and lack of team support. 

Refactoring Java Application: Object-Oriented And Functional Approaches

Java Refactoring Approaches

Refactoring in Java has many aspects, but among all of them, there are two fundamentals: object-oriented and functional. Object-oriented existed almost from the first Java version, whereas functional appeared only with Java 1.8 (March 2014).

Object-Oriented (OO) and Functional Approaches

Java is a classical object-oriented language and allows the creation of flexible object structures. After Java 1.8 received functional features, it became capable to operate not only with objects or methods but with lambdas (which is executable code itself). In the functional world, you can operate with functions as with objects in the OO world.

How Continuous Integration Plays a Crucial Role In Business Agility

There Was a Lot of Hype About Business Agility

Unfortunately, Agility in business became one of the most hackneyed topics in IT. The main message was "Agility is Cool," and makes business flexible, reducing time to market. It's true. Why then do I raise this subject once again? Well, to show practical aspects and explain why continuous integration plays such an important role.

Business Agility Meaning

An Agile business is a business that is capable of reacting to a new environment and making changes quickly.

What Every Java Developer Should Know About Thread, Runnable, and Thread Pool

Multithreading Is Most Complex And Biggest Part Of Java

Multithreading chapters are the most difficult to understand and use in Java. Unfortunately, there are not that many sources where you can get all the answers. Meanwhile, concurrency knowledge is critically important. In this article, I explain the core aspects of multithreading that every Java developer has to know. In this part, we start with the Thread and Runnable subject.

Why Is Concurrency Knowledge So Critical?

You Can't Get Senior Java Job Without Good Knowledge Of Multithreading

Multithreading knowledge almost certainly is the subject of interviews for senior Java positions. Without a clear understanding of multithreading with and without hands-on experience, you most likely will fail.  

How to Estimate Object Memory Allocation in Java

Estimating Allocated Memory (Not Object Size)

Previously, I explained how to calculate an object's size considering OS binary or types of objects and primitives. In this article, I'll only review ways to estimate the size of already allocated memory for a given object. There are a couple of ways to do it. Here we review the most popular.

Estimating Memory Using Profiler

The easiest way to estimate the memory of some objects is to look right inside JVM's memory using a profiler such as Visual VM

Why Classical Singleton Is an Antipattern: How To Make It Great Again Using IOC

Classical Singleton Introduction

Classical Singleton is one of the most well-known structural patterns. It is widely used in production and is responsible for creating only one single instance. This pattern was mentioned in the GOF patterns book. How is it possible that it became an antipattern? Before we start, let's remember what a classical Singleton looks like.  

Classical Singleton Implementation

Classical implementation of Singleton assumes that class contains two things:

NullPointerException in Java: Causes and Ways to Avoid It

NullPointerException: the Most Common Exception

NullPointerException (NPE) is the most common exception in Java. The cause of this exception is known but looks like that in most cases developers prefer to ignore it and don't take any action. I personally expect that reasons for such behavior are the following: 

  • Most of the developers don't see any problem here and recognize all NPE exceptions as the developer's fault. 
  • Developers who are aware of this design problem don't know how to fix it. 

In this article, I'll explain what is the root of this problem and provide ways to fix that problem.

Protecting Java Application From Stealing Data and Source Code

Attack Scenarios

In this article, we review possible ways how to inject malware code in JVM/to sniff JVMs traffic/etc. The key objective of this article is to explain how to protect your application. The plan is to perform the next attacks:

  • Read sensitive data from the dump.
  • Steal source code by injecting malware in an external dependency.

Stealing Data From Java Dump

If someone got access to the Java process he might be able to read sensitive information like passwords or database addresses. Let's take a look into the next DataSource configuration:

Compile Time Safe Code – Java and JavaScript Examples

Compile Time Safe Code Is True Gem In Development World

Compile Time Safe Code is the code that has a guarantee that after compilation it will work as expected. Such code is valid by design. Some languages and frameworks give Compile Type-Safe (not Time) solutions but this article covers more than just Compile Type Safetiness. Keeping your code Compile Time Safe reduces the number of potential bugs and makes code more reliable.

Compile Type-Safe (Not Time Safe)

Compile Type Safeness gives a guarantee that all variables are assigned to values with the correct type. Meanwhile, Compile Time Safe code is a more general notion that assures developers that code is not just type-safe but consistent in general.

What BDD Is and Why You Need It: Java and Behavior Driven Development

Is Behavior Driven Development Just Another Religion?

You might hear about BDD but still don't have a clear understanding of what it is. Here I'll try to simplify the main ideas and provide clear examples. This article is useful not only for developers but all people involved in the development process like analysts, product owners, and even guys from the business.

BDD Makes Application Logic More Transparent

Low Transparency in Application is a very known problem in IT. Quite often domain knowledge belongs only to the development team. As a consequence, to get even a simple answer you have to ask the developer to explain.

Java Immutable Explained. Immutable Objects With Examples.

What This Article About

Immutability is a broad concept and has many angles. Immutability is a set of practices that potentially might reduce the number of bugs in your application. As a consequence, this subject invokes confusion. Here, we review it from a different perspective. I'll explain the most important immutability aspects in clear language.

Mutability Problems Examples

Before we start, let's review two examples. They are pretty artificial but explain potential problems with mutable code:

Turing Machine: Prototype of Programming Language by Alan Turing, the Father of IT Era

Programming Language Roots

Nowadays programming languages are recognized as something ordinary, which does not come as a surprise. But in general, this technology is relatively young and appeared about 50 years ago. The first abstract idea of a programming language was introduced in mathematics. There are many related notions, such as a state machine, computer algorithm, and combinational logic, that have been introduced in mathematics and after defining the notion of the Turing machine.

Founder of IT Era: Alan Turing

Alan Turing, the Father of computer science, invented the Turing machine in 1936. Alan Turing is a legendary person who anticipated the IT era and became its founder. He is also known as a person who cracked the Enigma code and brought significant value to the second World War victory. His prediction that programming languages will be a part of normal life before the year 2000 was unthinkable during the years of his life.

How To Pass a Technical Interview: Recommendations and Win Strategy

Candidates

What This Is Article About

Maybe you were or you will be a candidate for a technical interview. Here, I'll share my personal experience as an interviewer. I'll share the best strategies to pass technical interviews considering the interviewer (company) side.  I'm sure both juniors and seniors could learn something from this article.

Earlier I published an article with recommendations on how to conduct technical interviews for interviewers. In that article, I recommended asking high difficulty questions first and then moving to simpler questions. In such a way, the interviewer can identify the candidate's knowledge quite quickly. However, this approach has one disadvantage: interviewed developers might experience a lot of stress. For this reason, companies may follow a different approach.

Java JMS Oversimplified

Java Messaging Service

JMS or Java Messaging service is a solution for asynchronous communication using messages (objects). Initially, it was part of JSR (specification used in Java EE).

Simple Problem as Example to Explain: User Creation Service

Let's assume we have any service that can process only 100 requests per second. Any higher load will freeze service or put it down.