Java Concurrency in Practice – Thread Safety

In my last post, Java Concurrency in Practice: Study Notes, I finished my writing with a statement that all code paths accessing a shared state must be thread safe. But, what is thread-safety? A piece of code is said to be thread-safe when it continues to behave correctly when accessed from multiple threads. To put it in a slightly more formal way:

“A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code” [JCiP].

At the heart of the definition, there is something we call: correctness. As we programmers often don’t get precise specifications we have to define correctness as something we recognize when we see it – the code works. Since a single-threaded environment is just an edge case of a multi-threaded environment. A program, class, or any piece of code “cannot be thread-safe if it is not even correct in a single-threaded environment” [JCiP].

Let’s continue with an another definition:

“stateless objects are always thread-safe” [JCiP].

But, what do we mean by the state of the object? An object’s state includes any data that can affect its externally visible behavior.

“An object’s state is its data, stored in state variables such as instance or static fields. An object’s state may include fields from other, dependent objects” [JCiP].

For example, a HashMaps state is defined not just by its fields but also by the state of the key value pairs it contains. Now, let’s suppose that we have an object with a state accessible from multiple threads. We often define a set of actions over the object with pre- and post-conditions, invariants, that must hold true before or after any action. These invariants rule out part of the objects state space as invalid. If an object is correctly implemented, no sequence of operations can get the object into an invalid state.

Change of state might be tricky. Often, what seems like a single action operation, it might not be atomic, which means that it does not execute as a single, indivisible operation.

“Operations A and B are atomic with respect to each other if, from the perspective of a thread executing A, when another thread executes B, either all of B has executed or none of it has” [JCiP].

In the CarFactory example below the state of the factory instance is represented by the member variable nextId. The code below looks totally innocent until we realize that incrementing variable nextId is not an atomic operation. It consists of three separate actions: fetch the current value, add one to it, and write the new value back. If multiple threads can access the CarFactory instance with some unlucky timing two cars can get the same id. Depending on the application this can have fatal consequences.

...
@NotThreadSafe
class CarFactory {

  private long nextId = 1;
 
  public Car createCar() {
    Car c = new Sedan();
    c.setId(nextId++);
    return c;
  }
  ...
}

The possibility of getting incorrect results by unlucky timing is so important in concurrent programming that it has a name: a race condition.

“A race condition occurs when the correctness of a computation depends on the relative timing or interleaving of multiple threads by the runtime” [JCiP].

To avoid race conditions, there are multiple ways to prevent other threads from using a variable while we’re in the middle of modifying it. Our aim is to ensure that other threads can observe or modify the state only before we start or after we finish, but not in the middle. One way to make our CarFactory thread safe is to use the AtomicLong library class. Because method getAndIncrement ensures atomicity now we don’t have to worry about unlucky timing. Annotations @NotThreadSafe and @ThreadSafe are not part of the standard jdk. They are used throughout this article and in the book to differentiate between safe and unsafe patterns.

...
import java.util.concurrent.atomic.AtomicLong;

@ThreadSafe
class CarFactory {

  private AtomicLong nextId = new AtomicLong(1);
 
  public Car createCar() {
    Car c = new Sedan();
    c.setId(nextId.getAndIncrement());
    return c;
  }
  ...
}

But what happens if the state of the object is shared among multiple variables? Is it enough to replace all member variables with their atomic version? Of course, not.

To preserve state consistency, update related state variables in a single atomic operation” [JCiP].

Locking helps us to preserve state consistency be ensuring that a critical section can only be executed by a single thread at a time. Java provides the synchronized block as a built-in locking mechanism.

synchronized (lock) {
   // Access or modify shared state guarded by lock
}

Every java object has an intrinsic lock that can be used for synchronization purposes. This internal lock is automatically acquired when entering a synchronized block and automatically released when leaving the synchronized block – even if it is by throwing an exception. A special case of a synchronized block is when we make a whole method synchronized. By doing so, we synchronize on the objects intrinsic lock or in case of a static method the Class< ? > object is used.

Intrinsic locks are reentrant. If a thread tries to acquire a lock that it already holds, the request succeeds. Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis. Reentrancy is implemented by associating with each lock an acquisition count and remembering the owning thread.

From a performance point of view, locking has its own challenges. We will discuss them in detail in a later chapter. For now, just remember one simple rule:

“Avoid holding locks during lengthy computations or operations at risk of not completing quickly such as network or console I/O” [JCiP].

In the next post, I’m going to deal with sharing objects: memory visibility, immutability, what is safe and unsafe publication. Stay tuned!

Resource
[JCiP] Java Concurrency in Practice by Brian Goetz, ISBN-10: 0321349601

Java Concurrency in Practice: Study Notes

A Personal Standpoint

Not long ago a guy from the HR department of the company I work asked if I have interest interviewing candidates for open positions. And I said something like: “Sure, why not”. On the first couple of occasions, I was only an observant. I asked a question or two, but the interview itself was conducted by a more experienced colleague. Then I started doing interviews on my own over the phone and started taking up the leading role in face-to-face interviews. Of course, every interview is different and each interviewer has a favorite set of questions but more or less all interviews are conducted based on a script prescribing which specific topics should be visited. As I started taking more and more responsibility for interviews I noticed that there was a topic that made me very uncomfortable. Often I just asked a couple of basic questions or sometimes even skipped it “because of a time constraint”. You have probably guessed by now, it was: concurrency. Of course, I had a basic concept of what concurrency is and what are the main pitfalls. However, I only had limited knowledge and experience with writing concurrent Java programs. I thought to myself, it would a good time to study the topic of concurrency in Java until, from being a weakness, it becomes one of my strongest points.

Study. Ok, but from What?

One can learn a lot about concurrency in Java only by reading the documentation of concurrency related Java classes like java.lang.Thread. However, to get a broader picture and a detailed explanation I was looking for a good book to learn from. After a little bit of googling, I’ve noticed that most of the sources point to a single book: Java Concurrency in Practice by Brian Goetz [JCiP].

Java Concurrency in Practice book cover
Java Concurrency in Practice by Brian Goetz

After reading the book I can say that it wasn’t a coincidence. It’s a wonderful book: it’s deep but also written in a way that is easy to understand, and most common problems and their solutions are illustrated with code snippets. To put it simply: it’s a must read for every Java developer.

Study Notes

The best way of acquiring new knowledge is not just to read books, but also to take notes. By doing so our brain is “forced” to process the new information once more. This is one of the reasons why I did other books on this as well – check posts in the Bookshelf Category. Another reason is that I hope others can benefit from my notes too. If you don’t have the time to read the full book, or you are not sure if it worths the time: just check my notes. In this case, I decided to go chapter-by-chapter because there is so much to process. I’ll present my notes from each chapter on a weekly basis. It won’t take more than 5-10 minutes to read them and at the end, I’ll share some extra content too. Without any further due, here comes the first chapter.

Chapter 1: Introduction

Writing concurrent programs is hard, to maintain them is arguably even harder: So, why bother with concurrency in the first place? In a nutshell: it is the easiest way to tap the computing power of multiprocessor systems, and often it is easier to write a complicated asynchronous program by writing multiple pieces of code that run concurrently but each doing only a single well-defined task.

The main motivating factors behind the development of operating systems that allowed multiple programs to execute simultaneously were:

  • Resource utilization – programs sometimes have to wait for external events that are out of they control. For example, an I/O operation to finish. While waiting for other programs might do some useful work.
  • Fairness – multiple users and programs may have equal claims on the computer’s resources. In a multi-user or multi-process environment, it’s more desirable for each program to get a chance to do some work than to wait for one program to run to finish and then start another.
  • Convenience – “It is often easier or more desirable to write several programs that each perform a single task and have them coordinate with each other as necessary than to write a single program that performs all the tasks” [JCiP].

Individual programs run in isolated processes: resources such as memory, file handles, and security credentials are allocated by the operating system separately. If they needed to, processes could communicate through means of inter-process communication: sockets, signal-handlers, shared memory, and files. “The same concerns (resource utilization, fairness, and convenience) that motivated the development of processes also motivated the development of threads. Threads allow multiple streams of program control flow to coexist within a process. They share process-wide resources such as memory and file handles, but each thread has its own program counter, stack, and local variables.” [JCiP]

In most modern operating system the basic unit of scheduling is the thread – not the process. All threads within a process have access to the heap that allows fine grained inter-process communication. However, uncoordinated access from multiple threads can leave shared data in an inconsistent state, resulting in undefined program behavior.

Java’s built-in support for threads is a double-edged sword. On one hand, it simplifies the development of concurrent applications. On the other hand, developers need to be aware of thread-safety issues. “Thread safety can be unexpectedly subtle because, in the absence of sufficient synchronization, the ordering of operations in multiple threads is unpredictable and sometimes surprising” [JCiP]. Fortunately, Java provides a number of synchronization mechanisms to coordinate shared access. But, in the absence of such synchronization, “the compiler, hardware, and runtime are allowed to take substantial liberties with the timing and ordering of actions, such as caching variables in registers or processor-local caches where they are temporarily (or even permanently) invisible to other threads” [JCiP].

When writing concurrent applications one must never compromise on safety, we must ensure that “nothing bad ever happens”. Although, that is desirable we also want to make sure that “something good eventually happens”, meaning that the program should not get into a state where it is permanently unable to make progress. On top of that, we often want “good things to happen quickly”. It really would be a waste of effort to rewrite an application to use multiple threads and end up with a program with a worse performance than the single-threaded version.

Threads are really everywhere. “When the JVM starts, it creates threads for JVM housekeeping tasks (garbage collection, finalization) and the main thread for running the main method” [JCiP]. Sometimes concurrency is introduced by using frameworks. The developer writes the business logic which seems to be a simple sequential order of steps (see. convenience as a reason for concurrency) but when it is plugged into the framework it might execute in parallel with other tasks, thus requiring that all code paths accessing shared state be thread-safe.

Elasticsearch: Getting a List of Distinct Values

I started using Elasticsearch a little more than a year ago. Elasticsearch is a distributed, open source search and analytics engine, designed for horizontal scalability, reliability, and easy management[1]. It has a very good, easy to use RESTful API so, you can use it with any web client. However, from Java I prefer to use the dedicated Java API. Recently I was working on indexing e-mails with a special focus on labels associated with the messages. Despite the Elastic API is pretty well documented, it took me a good amount of googling to figure out how to get back a list of unique labels. In Elasticsearch documents (in my case the e-mails) are organized into indices and to get back a list of distinct values of a property (e-mail labels) we need to use the so-called aggregation API. Here’s my solution:

import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;

public class AggregationRepository {
  private Client client;

  public AggregationRepository(Client client) {
    super();
    this.client = client;
  }

  public List getDistinctLabels() 
    throws InterruptedException, ExecutionException {
    SearchRequestBuilder aggregationQuery = 
      client.prepareSearch("emails")
        .setQuery(QueryBuilders.matchAllQuery())
        .addAggregation(AggregationBuilders.terms("label_agg")
          .field("labels").size(100));
    SearchResponse response = aggregationQuery.execute().get();
    Aggregation aggregation = response.getAggregations().get("label_agg");
    StringTerms st = (StringTerms) aggregation;
    return st.getBuckets().stream()
      .map(bucket -> bucket.getKeyAsString())
      .collect(toList());
  }
}


This is how the search query posted to the API looks like:

{
  "query" : {
    "match_all" : { }
  },
  "aggregations" : {
    "label_agg" : {
      "terms" : {
        "field" : "labels",
        "size" : 100
      }
    }
  }
}


And the response is…

{
  ...
  "aggregations": {
    "label_agg": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Gmail",
          "doc_count": 1
        },
        {
          "key": "Yahoo",
          "doc_count": 1
        }
      ]
    }
  }
}


Just to give a little bit of explanation: label_agg is the name of the aggregation – you can choose it however you wish. The results are coming back as buckets and the keys collected into a list gives us the list of unique labels. Of course, the aggregation API is capable of much more. This was just a simple example how to select distinct values from documents stored in Elasticsearch.

Resources

  1. Powering Data Search, Log Analysis, Analytics https://www.elastic.co/products

Crossing the Chasm by Geoffrey A. Moore

“First, there is a mountain, Then there is no mountain, Then there is.”

Is this some kind of magic trick? Nope, this is how business to business marketing works in the high tech industry. And this what Crossing the Chasm book is about: marketing and selling technology products to mainstream customers.

Before you stop reading because “marketing is not for me”, I promise it’s going to be interesting just bear with me for a little longer. In fact, I think every developer should read that book to get a wider perspective on what happens with the code we write. How it becomes a real product and how marketing decisions can drive a product with superior technology into the ground while a seemingly inferior product triumphs.

Crossing the Chasm book cover
Crossing the Chasm book cover

Disruptive Innovation

First, we have to understand the distinction between continuous and discontinuous or disruptive innovation. BMW offering a faster, more dynamic gasoline car with a slightly better design is an example of continuous innovation. In contrast, all electric cars from Tesla represent a discontinuous innovation. Because they demand significant changes not only by the customer but also by the supporting infrastructure. We cannot just stop, fill up our electric car and be on our way in a matter of minutes – or at least not for now. We need to stop for like 30 minutes maybe have a bite while our car gets charged. In exchange, we get a cleaner, more sustainable and more efficient form of transportation.

The Technology Adoption Life Cycle

“The Technology Adoption Life Cycle model describes the market penetration of any new technology product in terms of a progression in the types of consumers it attracts throughout its useful life. The groups are distinguished from each other in terms of how they react to disruptive innovation.”

Innovators or technology enthusiasts pursue technology products simply for the pleasure of exploring the new capabilities they provide. Early adopters or visionaries appreciate the benefits of a new technology. They typically have a greater vision and they see how a new technology product could support their goals. The early majority shares the early adopter’s ability to relate to technology, but they are driven by practicality. They want to see how other people making out before they invest substantially. The late majority is even more conservative they wait until the new technology becomes a standard. Laggards are people who only buy the technology when it becomes a necessity or when it’s so deeply integrated with something existing that they don’t even know they bought it. Each group has a unique psychographic profile – price sensitivity, expectations, and priorities. Therefore selling products to customers in each group requires fundamentally different approach and marketing communication.

Discovering the Chasm

As we work ourselves through the technology adoption lifecycle we discover that the psychographic groups are divided from each other by gaps. “This symbolizes … the difficulty any group will have in accepting a new product if it is presented in the same way as it was to the group to its immediate left”. The biggest disconnect is between the innovators and the early majority – this is the chasm that many start-up ventures have fallen into. And because there are so many business customers on the right side of it crossing the chasm is fundamental to making any significant profits.

Visionaries or innovators expect a radical discontinuity between the old ways and the new, and they are prepared to fight the resistance. They are prepared to bear with the inevitable bugs and glitches of the new product. By contrast, what early majority wants is a productivity improvement for existing operations. They do not want to debug someone else’s product. They are looking for a solution integrated with current systems. Because of these incompatibilities, visionaries do not make good references for early majority. The only suitable reference, it turns out, is another member of the same group. This leads us to a catch-22 situation which needs to be solved because references play an utmost role in buying decisions of early majority customers.

Crossing the Chasm

To cross the chasm high technology companies need to launch a D-day type of invasion where they first focus on a single niche market segment to secure the beachhead. All development and marketing efforts should be focused on a single target. This is the only way to cross the channel … sorry, the chasm. Once the beachhead is secured you can advance to adjacent market segments until you become the market leader. But how to choose which beachhead to attack? You will need to select a market segment with an acute problem and provide a solution that current mainstream products cannot provide. They neglect a particular segment perhaps because they can make a tremendous amount of profit with a more general product.

Let me illustrate this with an example from the book. When farmaceutical companies introduce a new drug they deal with a very complicated documentation process. They were often delays just because the tracking and versioning of the documentation was a nightmare. Then came a company called Documentum that solved this literally million dollars a day problem. Guess what, effective document handling is also important in a number of other niches like finance, human resources etc. The trick is once you dominate a segment with customers of the early majority they serve as a very good reference for the same type of customers in adjacent segments.

Creating the Competition

When choosing the point of attack try to select a small pond where you can be the big fish. Of course, the pond should be big enough to keep you alive. And in any big enough pond there will be a competition. But competition is good, in fact, pragmatists resist to buy until they can compare. You will need two companies to put your product on the map like GPS satellites tell your position on the globe. One of them is the market alternative with established customer base you are after. This could be for example Microsoft SharePoint in document sharing. The other is the product alternative also harnessing the same disruptive innovation as your solution. This could be something like Dropbox with its ease of use and polished user experience. By pointing out that there is a product alternative you also weaken the position of the market alternative company. This is done by giving customers the notion that there is an undergoing paradigm shift in the marketplace. Your intent should be to acknowledge this new technology but to differentiate from the product alternative by virtue or your own segment focus.

Leaving the Chasm Behind

There is a sad revelation to make once you have successfully crossed the chasm. People who made this breakthrough possible most probably won’t carry you forward. Rockstar developers will want to work on the “next big thing” and salespeople who are able to sell to visionaries might not be as successful with conservatives. This transition won’t happen overnight but it will happen almost inevitably.

Personal Notes

I found two things very interesting in the book: subsequent editions after the first one haven’t been written because market dynamics have changed significantly. They work nearly the same way today as they were in 1991 when the book was first released. The reason for new editions was that companies come and go and the examples in the book had to be updated. Who heard of Lotus or Silicon Graphix? Will Facebook be still known in 10, 20 or 25 years time? Maybe, maybe not. It always fascinates me how fast paced our industry is.

The second thing is: the D-day type strategy might work withing a single enterprise just as well as in the wider market. I see a fractal pattern where departments inside a firm behave as adjacent market segments at a smaller scale. Departments working with less business critical applications will adopt any new technology first. Once it’s established at least in one department it will be easier to sell the technology to other department heads.

As a closure, I would like to recommend this book to developers and owners of small technology companies. A strategy that proved itself many times with big companies can be applied on a smaller scale as well. It might not be the same league but it surely is the same game!

5 Tricky Questions from Java

While I was studying for the Java 8 OCA exam I’ve come across some questions that really confused me the first time I saw them. Here is a short list of five tricky questions you might expect on an exam or during a job interview.

The Assignment Operator

What will happen when you try to compile and run the following pieces of code independently?

Snippet #1

int i = 1;
i = i + 2.5;
System.out.println(i);

Snippet #2

int i = 1;
i += 2.5;
System.out.println(i);
  1. Both result in compile time error
  2. Both compile successfully and print 3
  3. Both compile successfully and print 3.5
  4. First snippet fails to compile; the second one compiles and prints 3

Answer

The first snippet fails to compile because expression i + 2.5 results in a double value that cannot be stored in an integer variable. You might think that the second code snippet does the same thing. However, that’s not the case. The assignment operator += not just combines the assignment and addition in order to look cooler but also casts the result of the right-hand side if required – in our case back to integer. So, option D is correct. Please note 3 is printed instead of 3.5 as variable i is of type integer.

Indexing Arrays

Consider the following class:

class Test{
   public static void main(String[ ] args){
      int[] x = { 1, 2, 3, 4};
      int[] y = { 0, 1, 3};
      System.out.println( x [ (x = y)[2] ] );
   }
}

What will it print when compiled and run?

  1. It will throw ArrayIndexOutOfBoundsException
  2. It will print 4

Answer

When indexing arrays, the expression to the left of the brackets is fully evaluated before any part of the expression within the brackets is evaluated. This means that the original value of x is fetched and remembered while the expression (x = y) [2] is evaluated. So, option B is correct. Value 4 is printed out from the first array.

Null Reference

What do you think will be the result of trying to compile and run the following code?

class A {
     public static void print(Object obj) {
          System.out.println(obj);
     }
     public static void main(String[] args) {
          A a = null;
          a.print(a);
     }
}
  1. Compile error
  2. NullPointerException is thrown at runtime
  3. Compiles and runs without an issue and prints null

Answer

Option C is correct. Please note that the print method in class A is static. It doesn’t matter that variable a has a null value the method is executed based on the type of the variable.

Date Manipulation

What will be printed out by running the following code?

LocalDate date = LocalDate.of(2016, Month.AUGUST, 20); 
Period period = Period.ofMonths(1).ofDays(1); 
LocalDate past = date.minus(period); 
System.out.println(past.format(DateTimeFormatter.ISO_DATE));
  1. 19 Aug 2016
  2. 2016-08-19
  3. 2016-07-19

Answer

The trick here is that Period.ofMonths(int) and Period.ofDays(int) are static methods, therefore they cannot be chained. So, the period subtracted from the date represents only one day without the month. The correct answer is option B. Please notice the ISO_DATE format too. Option A would be correct if we used DateTimeFormatter.ofPattern("dd MMM YYYY").

String Pool

What will be the result of attempting to compile and run the following code?

if ("true".replace('T', 't') == "true" 
     System.out.println("true"); 
else
     System.out.println("false"); 
  1. It will print “true” 
  2. It will print “false”

Answer

When comparing two strings with the == operator we ask whether they are pointing to the same object. The two "true" literals on the first line represent the same object from the string pool. When we call the replace method on the first "true" it returns a String object in which all occurrences of the first parameter are replaced with the second parameter. However if there is no change to be made the reference to the same object is returned, therefore option A is correct – the code above prints "true". If we changed the first line to if ("true".replace('t', 'T') == "True") the code would print "false" because the "True" returned by the replace method would be a new String object.

These were my favorite tricky Java questions. Of course, there are tons of questions that can be asked. The 5 questions above are really just the tip of the iceberg. Anyway, I hope this helps you regardless whether you are preparing for a Java exam, your upcoming job interview, or you’re just a Java enthusiast like I am. 

7 Habits of Highly Effective People by Stephen R. Covey

I’ve read this magnificent book recently and I would like to share some of my findings with you. It’s going to be less of a formal review but rather an ad-hoc collection of subjective thoughts about the ideas presented in the book. You may say: “this is just one those worthless self-help books” or “This is just another scam”. But I can assure you nothing is further from the truth. This book can really help those who seek ways to improve their personal and business relationships, or simply just want to better understand themselves and their place in the world.

The 7 Habits of Highly Effective People book cover
The 7 Habits of Highly Effective People by Stephen R. Covey

The core of the book 7 Habits of Highly Effective People consists of two parts: private and public victories. This division catches the essence of the revelation that in order to be successful in our interpersonal relationships we first need to build our own character. You cannot win by hacking at the leaves without taking care of the problems at the root. Now let’s have a look at the 7 habits of highly effective people.

Habit 1: Be Proactive

Act and not be acted upon. So simple, but so powerful. Arguably one of the greatest sources of frustration is that we feel like we are not in control of our own life. The book says: “we find two ways to put ourselves in control of our lives immediately. We can make a promise – and keep it. Or we can set a goal – and work to achieve it“. By doing so, we build a character that will serve as a strong foundation we can build upon.

Habit 2: Start with the End in Mind

How would like to be remembered after you are gone? What kind of husband, wife father, mother, colleague or friend were you? Did my yesterday behavior bring me closer to what I’ve just imagined who I want to be? If you start with the end in mind you will find yourself working towards your life goals and not wandering on side roads. “People may spend their whole lives climbing the ladder of success only to find, once they reach the top, that the ladder is leaning against the wrong wall.

Habit 3: Put First Things First

For the many of us, and I’m no exception, there is a deep chasm between what we say are important things to us, and how we actually allocate our time. That’s not always as evident as choosing between going to a gym or watch another episode of our favorite TV show. Sometimes we think: oh, it would be very important to read that book or take that course, but I’ll do these million little things first.
To say yes to important priorities, you have to learn to say no to other activities, sometimes apparently urgent thigs.” And it’s tricky because finishing up little tasks gives us the feel of progress while we are neglecting other things that would contribute to our long-term growth. Put first things first is the last one of private victories.

The first 3 habits are concluded with an analogy to which IT people can easily relate too. We need to realize that we are the “programmers” of our own life (habit 1). We need to “write” the program with the desired end result in mind (habit 2). Then we need to “execute” (habit 3). Each step builds upon the previous one, just like developing personal victories serves as a foundation for public victories.

Habit 4: Think Win-Win

Who is winning in your marriage? is a ridiculous question. If both people aren’t winning, both are losing.” Life, in most cases, is not a zero sum game. For you to win another person does not necessarily have to lose. Most people are scripted in scarcity mentality – there is only one pie out there, and if someone were to get a piece, it would mean less for everybody else. This is how mediocre people see the world. On the other hand, people with abundance mentality realize how sharing of prestige, recognition, and profit springs new possibilities for even greater successes. Having abundance mentality is essential to be able to think win-win.

Habit 5: Seek First to Understand Then to be Understood

Since our childhood, we put tremendous efforts into improving our communication skills both written and verbal. But what about listening? “Most people do not listen with the intent to understand; they listen with the intent to reply”. To try to help somebody without seeing things from the other person perspective first is like prescribing medicine without examination. Our ability to think win-win is greatly affected by how carefully we intend to listen. It happened to me in the past, probably more than once, that a UI developer came to me complaining about the API I wrote as a backend developer. It didn’t make any sense to me. I was thinking: “It suits the requirements why can’t he just use it!” Now I know, I couldn’t understand him because I didn’t intent to listen.

Habit 6: Synergize

What is synergy? Simply defined, it means that the whole is greater than the sum of its parts. It means that the relationship which the parts have to each other is a part in and of itself.” By exercising habits 4 and 5 we often reach a synergistic solution that is better than either of the originally proposed ones. “The essence of synergy is to value the differences. Sameness is not oneness; uniformity is not unity.” Probably the aforementioned API would have turned out to be much better if a synergistic solution had been reached.

Habit 7: Sharpen The Saw

If you take a little time to sharpen the saw you will be able to cut down a tree much faster. It’s a very simple principle, but still, people often fail to recognize it in their own life. “Going to the gym takes to much time”. Well, how much time will you spend at doctors if you ruin your health? Sharpen the saw is basically improving our production capability today. Because for the great struggles of the future, you have to prepare today.

These are the 7 habits of highly effective people by Stephen Cover. Of course, the book goes into greater lengths and explains each topic in much more detail. The book is enriched with real life stories about the author’s family. Reading these stories was full of aha moments when I realized that something similar has happened to me in the past and now I can understand why things played out as they did. The cool thing about these stories is that the author does not try to hide his own mistakes. We learn that sometimes he failed to respond to a given situation in harmony with the seven habits. However, sincerely admitting our mistakes is not a weakness but quite the contrary a manifestation of great strength. Remember: success lies on the far side of failure.

How to Pass Java 8 OCA Exam – Part 2

This is the second a final part of my writing on how to pass the Oracle Certified Associate Exam from Java 8. In case you haven’t read the first part you can do it here: How to Pass Java OCA 8 Exam – Part 1.

After I finished reading the official study guide I was looking for some tests I can practice on. I came across a software produced by a company named Enthuware. They offer a free testing framework and charge you for the question packages. Please make sure you download the Java 1Z0-808 package because this is what you will need. Compared to the price of the exam the cost of the package is very reasonable and represents a good value. The application offers multiple testing options but let’s get into that a bit later.

Week 3

Goal: Finish Enthuware objective-wise test 1-5; take standard test 1-3.

Monday Take Entuhware Standard Test 1 77 Hardcoded Questions
Tuesday Take Objective-wise Tests 1-2 Java Basics and Data Types – 40 Questions
Wednesday Take Standard Test 2 77 Hardcoded Questions
Thursday Take Objective-wise Tests 3-5 Operators, Arrays and Loop Constructs – 40 Questions
Friday Take Standard Test 3 77 Hardcoded Questions

By week number 3 you should have all the required lexical knowledge. So, you can move onto practicing sample tests. This is where you will need the Enthuware software. After installing the correct question package (make sure you download 1Z0-808) you can choose from several types of tests. Standard tests are the big ones. Answering 77 questions and reviewing the answers takes about 2 – 2,5 hours. It’s very demanding – I know. This is why I included “lighter” days between two big tests. The objective-wise practices roughly correspond to the chapters in the OCA book and help you to revise your knowledge.

Week 4

Goal: Finish off all the objective wise tests and standard tests up to #5.

Monday Take Objective-wise Tests 6-7 Constructors, Methods, Encapsulation, and Inheritance – 40 questions
Tuesday Take Standard Test 4 77 Hardcoded Questions
Wednesday Take Objective-wise Tests 8-11 Exceptions, Instanceof Operator, Java APIs and Lambda Expressions – 35 Questions
Thursday Take Standard Test 5 77 Hardcoded Questions
Friday Take the Easy Practice Test 30 Questions

This week is a continuation of the previous one and it is very demanding but it wall pay off.

Week 5

Goal: Finish off all Enthuware tests and go back to the OCA book to identify any weak spots.

Monday Take Standard Test 6 77 Hardcoded Questions
Tuesday Take the Though Practice Test 30 Questions
Wednesday Take the Very Though Practice Test 27 Hardcoded Questions
Thursday Take OCA Tests for Chapters 1 – 3
Friday Take OCA Tests for Chapters 1 – 6

For the last 3 weeks, you have been taking tests from the Enthuware testing framework. Now it’s time to go back to the OCA book for some change. Taking earlier objective-wise tests again helps you to identify areas of development, topics in which you are still not confident enough. You should answer all the questions and calculate the percentage of correct answers for each. Then you will need to re-visit chapters for tests with the two lowest scores. I really recommend to read through the chapters just as I did or at least identify the most relevant sections. For the last three days, I reserved three online tests. By buying the official study guide you automatically get access to 3 online tests. You will need to visit the site of the publisher – Sybex test bank – and take the practice exams from there.

Week 6

Goal: Fix weak spots and test again

Monday Re-visit the chapter where you scored the lowest
Tuesday Re-visit the chapter where you scored the second lowest
Wednesday Online Test 1 60 Questions
Thursday Online Test 2 60 Questions
Friday Online Test 3 60 Questions

You may say that I ran through the book very quickly and focus too much on the tests. The reason for this that is twofold:

  • I was already familiar with the basic concepts as I program in Java almost every day.
  • At the end of the day, the certification exam will be a test 😉

If you are new to the language you may need to spend more time with the study guide perhaps take fewer practice tests. It all comes down to your proficiency with the Java language. But one thing is sure: after week number 6 you should feel proud. After countless hours spent in front of tests, you are ready to go and take the real thing.

I Hope you find this post useful and I wish you good learning!

How to Pass Java 8 OCA Exam – Part 1

In this article, I’ll give you a step-by-step approach how to pass Java 8 Oracle Certified Associate exam. I’ll explain my method, how I scored 94% on this exam. For more on what this exam is or whether it’s worth taking it see my previous post: Should I become a Certified Java Developer?

There are two keys to success in taking exams. On one hand, you have to have the lexical knowledge. On the other hand, you have to be familiar with the way the exam is going to test your competence. Knowing upfront what kind of tricky questions to expect might mean the difference between passing or failing the exam. It’s better to be prepared because sometimes even the wording of the questions might be confusing.

The official study guide: Oracle Certified Associate Java® SE 8 Programmer I will help you with the lexical knowledge. It covers all the topics that are on the exam and nothing more. It’s very well written and easy to follow even for beginners. I strongly suggest buying a hard copy or download it as an e-book. After each chapter, there is a set of review questions to test your understanding.

The decision to take this exam takes courage, passing it successfully takes commitment and effort. I was wondering what technique I could use to improve my chance of success. At the end came up with a 6-week program similar to what personal trainers use to get you in shape. However, this program will exercise your brain instead of your muscles. Each day has a task assigned to it, but nothing is carved in stone. This program incorporates flexibility – the ability to respond to unforeseen events that otherwise might get you off track. This program is broken down into weeks and you should focus on accomplishing weekly goals – rather than worrying about missing a day or two. However the closer you can stay to the schedule the easier the process will be. Now let’s have a look at the step-by-step approach how to pass Java 8 OCA exam.

Week 1

Goal: Finish the first half of the study guide.

Monday Read Chapter 1 Java Building Blocks
Tuesday Answer Review Questions for Ch. 1
Wednesday Read Chapter 2 and Answer Review Questions Operators and Statements
Thursday Read Chapter 3 Core Java APIs
Friday Answer Review Questions for Ch. 3

You may go faster or slower. I followed this routine while working full-time.Depends on how fast you read but one chapter should be manageable in one day. If you need more time use a portion of the day reserved for answering review questions. One thing is very important, please check your answers for mistakes and make sure that you understand why you answered incorrectly before finishing a review day.

Week 2

Goal: Finish the second half of the study guide

Monday Read Chapter 4 Methods and Encapsulation
Tuesday Answer Review Questions for Ch. 4
Wednesday Read Chapter 5 and Answer Review Questions Class Design
Thursday Read Chapter 6 Exceptions
Friday Answer Review Questions for Ch. 6

As you probably have noticed I assigned more work to Wednesdays just to push myself a little harder, but I left the weekends empty. If you need more time to catch-up feel free to use the weekends. If you need some rest that’s also fine. Just make sure you stay focused.

By coming this far we have finished the official study guide. But, this is just the start, in the second part I’ll come back with more advanced stuff. Stay tuned.

Should I Become a Certified Java Developer?

The number of software developers doubles roughly every 5 years. Until artificial intelligence reaches a level where computers will be able to program themselves more and more programmers will be needed. There are tons of initiatives to teach programming not just for children but even for adults. But which programming language one should learn? If you would like to develop for mobile phones. Apple’s Swift language is a good start. Would you like to build online stores or blogs? Then PHP is a good pick. A lot of small and mid-sized companies build web services in C#. But is there a language in which you can do all of that, plus have a knowledge in your hand that is applicable from Wall Street to Silicon Valley? That would be Java, the programming language that is around from 1996 and will be for the foreseeable future.

robot thinker artificial intelligence progress pop art retro style. antique pose. science fiction and the robot character.

Oracle is the company behind Java and as such it organizes certification exams for developers. Because there is a lot of content to cover you have to pass two exams to become a certified Java developer: the Certified Associate (OCA) and the Certified Programmer (OCP). You can do it in any order you wish but keep in mind that the OCA exam is about the basic principles while OCP focuses on more advanced concepts. So, it makes sense do take them in that order.

In my opinion certification programs provided by Oracle should serve as a common denominator for Java developers. Sure, you can write good code without taking these exams. You can do it even without going through any formal education. But, how would you feel if your doctor or lawyer didn’t have any papers to prove they know what they do? More established professions already regulated themselves in order to guarantee the highest possible quality of services. Computer programming is still a very young field of profession. However, it’s only a matter of time when education and certification exams will play utmost importance. As Robert C. Martin the author of popular books like the Clean Code puts it: “we better regulate ourselves before politicians do”. The community of software developers should establish rules for its members. One of such rules could be the list of exams, a programmer has to take in order to become a member.

Does it worth the effort to study and take the certification exam until it isn’t a must? If you are a new graduate fresh out of college and looking for a job, try to look at things from an HR person’s perspective. Having a certification might not get you the job, but it certainly will help you to get on the shortlist. Another option is that you are a programmer who works with Java for many years. In that case, you might think it’s not all that important to have a paper. I’m myself an example of the later, except that I have a different opinion about the exam. The language itself evolves constantly. We had to wait for Java version 8 a very long time but it introduced a good deal of new stuff. Studying for a certification exam is a very good opportunity to keep up with the changes.

If you work as a full-time developer the odds are that you are performing very similar tasks day by day, month after month: work with Hibernate, writing Java Web Services, designing Rest APIs or constructing Sybase queries. And there’s nothing wrong with that because you can become an expert in those areas. But on the other side you easily loose the broader picture – use the programming language in a very limited way and forget the fundamentals. I kinda felt this way. So, I decided to take the certification exam. Without a doubt, it was a very good decision. I learned a lot and I even noticed that I even started using new coding patterns. I hope you will follow me and experience a similar joy and excitement going through this truly transformational process as I did.

P.S. …and make no mistake, artificial intelligence will one day take our jobs.

Remotely Rich by Matt Vogel

“Do you want to make $450,000 a year as a Web developer?”

What a rhetorical question to start a book with. I started thinking right away: is that achievable by a combination of web development and affiliate marketing, or perhaps by developing your own product and selling it to big businesses? Actually, none of that turned out to be the case.


Book Cover - Remotely Rich

In his book Remotely Rich, Matt Vogel is sharing his practices and experiences of being a freelancer web developer working from home. But how can he make almost half a million dollars a year? The secret turns out to be more prosaic than you might think. Matt is saying that by managing his time properly and by cutting out all the disruption that is present in an office environment he is able to work three full-time jobs. And because freelancers tend to be paid more than regular workers the numbers add up. I’m pretty sure that anyone who ever worked in an office can testify that a significant portion of the day is spent in a breakout area – drinking coffee, tea or some other source of caffeine and sugar while discussing last weekend and planning the next one.

In contrast, Matt focuses on maximizing effectiveness. It’s not easy and he is painting a very realistic picture of what it takes to be a freelancer. Matt admits it can be difficult sometimes and occasionally it involves working crazy hours to meet a deadline. However, I could not help myself but think that, in one form or another, most of the challenges of being a freelancer is present at regular jobs too. Working on the weekend? Check. Do managers have unrealistic expectations or imperfect knowledge about the state of the project? Most of the time. I’m not saying that working in a nine-to-five job and being a freelancer are the same things, but there are similarities for sure. Probably handling clients is the biggest challenge that you don’t have to bother with when you are working for a company. I see that not every programmer would be willing to do that. However, maybe it would worth to git it a try given how financially rewarding freelancer life could be. There are some valuable tips and techniques in the book regarding how clients should be handled.

Matt in his book is being very practical and tells us about a lot of things from choosing office space down to personal hygiene (really). There is a section dedicated to advises on tax and financials. Because he is living in the US this section is less helpful for us who work outside the States. Although every developer should think about what to do with the money earned. Invest in stocks, bonds or index funds? Buying a real estate is an option too. Developers who are not confident with financials should seek professional advice.

Remotely Rich is not a long book to read. It’s very practical and down-to-earth. This book is more about core soft skills than programming techniques. I definitely recommend it to anyone who is thinking about starting a career as a freelancer web developer.


Amazon: Remotely Rich – How to Multiply Your Income As a Web Developer