Saturday, January 19, 2019

Java Concurrency - Atomic classes

Greetings!

Java let us use update operations on single variables in non-blocking, thready safe programming with Atomic variables. (atomic-package-summary)
This is like a enhanced version of volatile variables.

It should be note that these classes are not replacement for Integer and related classes.
These are not only thread safe, but also provides better performance than using synchronized blocks.

Source code for Synchronized vs Atomic classes performance can be found here.

Main classes,
  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicReference
Say we want a counter, AtomicInteger and AtomicLong has below methods.
  • incrementAndGet() - Atomically increments by one the current value.
  • decrementAndGet() - Atomically decrements by one the current value.

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicCounter implements Counter {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public void increment() {
        atomicInteger.incrementAndGet();
    }

    public void decrement() {
        atomicInteger.decrementAndGet();
    }

    public int value() {
        return atomicInteger.get();
    }

}


In addition to primitive types, this API provides atomic operations support for arrays using below classes.
  • AtomicIntegerArray
  • AtomicLongArray
  • AtomicReferenceArray


Friday, January 18, 2019

MongoDB - Basic Commands

Greetings!

These are the basic MongoDB commands we use in our day-today work. Adding as a reference to myself :)

Create database

use DATABASE_NAME
$ use my_database

Show databases

$ show dbs

Connect to database

use DATABASE_NAME
$ use my_database

Drop database

db.dropDatabase()

Create Collection

DB.COLLECTION_NAME.(OPTIONS)
$ db.products.({ name: "Fruit Juice" })

Show collections

$ show collections

Drop collection

db.COLLECTION_NAME.drop()
$ db.products.drop()

Insert document

db.COLLECTION_NAME.insert(DOCUMENT)
$ db.products.insert({
item_name: "Frui Juice",
item_description: "sdfsdklf",
price: "100"
})

Read document

db.COLLECTION_NAME.find()
db.COLLECTION_NAME.find().pretty()
$ db.products.find().pretty()
$ db.products.find({ item_name: "Fruit Juice" }).pretty()

Like statement - we have to use regex
$ db.products.find( { item_name: { $regex: /789$/ } } )

AND
$ db.COLLECTION_NAME.find(
   {
      $and: [
         { key1: value1 }, { key2:value2 }
      ]
   }
).pretty()

OR
$ db.COLLECTION_NAME.find(
   {
      $or: [
         { key1: value1 }, { key2:value2 }
      ]
   }
).pretty()

Update document

db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
$ db.products.update({
{ item_name: "Frui Juice" },
{ price: 120 }
})

Delete document

db.COLLECTION_NAME.remove(CRITERIA)
$ db.products.remove({})
$ db.products.remove({ item_name: "Fruit Juice" })

Projection

Selecting only required fields
db.COLLECTION_NAME.find({}, { FIELD_NAME: 1 })
$ db.products.find({}, { item_name: 1 })
_id field is always displayed.
$ db.products.find({}, { item_name: 1, _id: 0 })

Limiting records

db.COLLECTION_NAME.find().limit(NUMBER)
db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)
$ db.products.find({}).limit(5)
$ db.products.find({}).limit(5).skip(2)

Sorting records

db.COLLECTION_NAME.find().sort({ KEY: 1 })
1 - ascending, -1 - descending
default to ascending
$ db.products.find({}).sort({ title: -1})

Create index

db.COLLECTION_NAME.ensureIndex({ KEY:1 })
1, -1 are orders
$ db.products.ensureIndex({ item_name: 1 })


Java Concurrency - Executor Framework

Greetings!

What is the basic abstraction for creating threads in Java? Is it new Thread(new Runnable()) ? NO. It is Executors!
Decoupling is a good programming practice and it is better to separate thread creation from the application. Java's way of encapsulating these functions are known as executors. (Executors)

Executor Interfaces

  • Executor - simple interface used to submit new tasks
  • ExecutorService - sub interface of Executor which supports life cycle management of both of the tasks and Executor itself.
  • ScheduledExecutorService - sub interface of ExcecutorService which supports task scheduling.

ExecutorService

This has more features than Executor interface. Mainly it support thread pooling, return the result via Callable, shutting down the service.
  • execute(Runnable)
  • submit(Runnable)
  • submit(Callable)
  • shutdown()

This has following implementations in java.util.concurrent package.
  • ThreadPoolExecutor
  • ScheduledThreadPoolExecutor

Creating a ExecutorService can be done using Executors factory class.
ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(() -> System.out.println("running with executors"));

ScheduledExecutorService

This can be used to schedule given task after a given delay or periodically. Main methods are schedule, scheduleAtFixedRate, scheduledWithFixedDelay.

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.schedule(() -> System.out.println("running with a delay"), 1, TimeUnit.MINUTES);


Creating an Executor

Executors are created using Executors factory class in java.util.concurrent package. Which method we use is depending on our requirement.

  • Executors.newSingleThreadExecutor - ExecutorService with a single thread to execute tasks.
  • Executors.newCachedThreadPool - Creates a thread pool that creates new threads as needed. This creates a new thread if no thread is avaible and reuse an existing thread if they are avaible. Threads that have not been used for sixty seconds are terminated and removed from the cache.
  • Executors.newFixedThreadPool - Created thread pool that reuses a fixed number of threads. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.
  • Executors.newSingleThreadScheduledExecutor - ScheduledExecutorService with a single thread to execute tasks.
  • Executors.newScheduledThreadPool - ScheduledExecutorService with a fixed length thread pool.


ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
ExecutorService fixedExecutorService = Executors.newFixedThreadPool(10);
ExecutorService onDemandExecutorService = Executors.newCachedThreadPool();

ScheduledExecutorService singleScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService fixedScheduledExecutorService = Executors.newScheduledThreadPool(10);



Thursday, January 17, 2019

Java Concurrency - SimpleDateFormat Is Not Simple

Greeting!

Formatting, parsing dates is a painful task. It always give us errors :(.
A common way to format, parse dates in Java is using SimpleDateFormat. Here is a common class we can use.


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateUtils {

    public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    private DateUtils() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.format(target);
    }

}


Do you think this is working. Let's test it.


    private static void testSimpleDateFormatInSingleThread() {
        final String source = "2019-01-11";
        System.out.println(DateUtils.parse(source));
    }

    // Fri Jan 11 00:00:00 IST 2019


Yes, it worked. Let's try it with more threads.


    private static void testSimpleDateFormatWithThreads() {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        final String source = "2019-01-11";

        System.out.println(":: parsing date string ::");
        IntStream.rangeClosed(0, 20)
                .forEach((i) -> executorService.submit(() -> System.out.println(DateUtils.parse(source))));

        executorService.shutdown();
    }


Here is the result I got.


:: parsing date string ::

... omitted

Fri Jan 11 00:00:00 IST 2019
Sat Jul 11 00:00:00 IST 2111
Fri Jan 11 00:00:00 IST 2019
... omitted


Interesting result isn't? This is a common mistake most of us have done when formatting dates in Java. Why? because we are not aware of thread safety. Here is what Java doc says about SimpleDateFormat

"Date formats are not synchronized.
It is recommended to create separate format instances for each thread.
If multiple threads access a format concurrently, it must be synchronized
externally."

When we use instance variables we should always check whether it is a thread safe class or not.

Solution 1 - ThreadLocal

We can solve this by using a ThreadLocal variable. (more about ThreadLocal)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class DateUtilsThreadLocal {

    public static final ThreadLocal SIMPLE_DATE_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    private DateUtilsThreadLocal() {}

    public static Date parse(String target) {
        try {
            return SIMPLE_DATE_FORMAT.get().parse(target);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String format(Date target) {
        return SIMPLE_DATE_FORMAT.get().format(target);
    }

}


Solution 2 - Java 8 Thread safe Date Time API

If we really need to stick with SimpleDateFormat we can go ahead with ThreadLocal. But when we have a better option we should consider using it.
Java 8 comes with several Thread safe date classes.

And here is what Java docs says,
"This class is immutable and thread-safe."

It is worth to study more about these classes.
DateTimeFormatterOffsetDateTimeZonedDateTimeLocalDateTimeLocalDateLocalTime


import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateUtilsJava8 {

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private DateUtilsJava8() {}

    public static LocalDate parse(String target) {
        return LocalDate.parse(target, DATE_TIME_FORMATTER);
    }

    public static String format(LocalDate target) {
        return target.format(DATE_TIME_FORMATTER);
    }

}


One more thing to note here. It is a good practice to use immutable classes ;)

Complete source code

Happy coding....