Month: May 2017

ThreadLocal Example with Java 8

Posted on Updated on

What is ThreadLocal in Java?

ThreadLocal is a specially provisioned functionality by JVM to provide an isolated storage space for threads only. like the value of instance scoped variable are bound to a given instance of a class only. each object has its only values and they can not see each other value. so is the concept of ThreadLocal variables, they are local to the thread in the sense of object instances other thread except for the one which created it, can not see it.

Like request, session and application scope of any Object, We can define a Thread Scope of any Object thus Object visibility would be only within the Thread and Every Thread has it execution life cycle, After a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).

Although we usually create a Synchronize  Object for Thread safety in MultiThread application therefore only one Thread can be obtained a monitor to access shared Object Since shared Object is not thread safe.

In Java 8, A new method is introdued  to determine the initial value.

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

Here, a simple ThreadLocal example of Java 8 is demonstrated that how each Thread gets own ThreadLocal copy of variable and value remain same even in Iteration process and each thread are executing separately on the ThreadLocal variable.

 

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * Created by MYPC on 5/29/2017.
 */
public class ThreadLocalExample {
    private static final AtomicInteger transactionId = new AtomicInteger(10000);
    private static final ThreadLocal threadLocal = ThreadLocal.withInitial(() -> transactionId.getAndIncrement());

    public static void main(String[] args) {

        // Thread 1 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

        // Thread 2 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();
        // Thread 3 executing and getting same Transaction Id for all iteration
        new Thread(() -> IntStream.range(0, 3).forEach(val -> {
            System.out.println(Thread.currentThread().getName() + " > " + threadLocal.get());
        })).start();

    }
}
Execution Output :-

Thread-1 > 10001
Thread-1 > 10001
Thread-1 > 10001
Thread-0 > 10000
Thread-0 > 10000
Thread-0 > 10000
Thread-2 > 10002
Thread-2 > 10002
Thread-2 > 10002

Advertisements

Java 8 : How to calculate difference between two Dates.

Posted on

Java-8

 

 

 

Java 8 introduced Date and Time API that represents the principle date-time concepts, including instants, durations, dates, times, timezones and periods. They are also based on the ISO Calendar system and unlike their predecessor, class in java.time packages are both immutable and thread-safe. New date and time API is located inside java.time package and some of the key classes are following :

 

  • Instant – It represents a timestamp
  • LocalDate – a date without time e.g. 2014-01-14. It can be used to store birthday, anniversary, date of joining etc.
  • LocalTime – represents time without a date
  • LocalDateTime – is used to combine date and time, but still without any offset or time-zone
  • ZonedDateTime – a complete date-time with time-zone and resolved offset from UTC/Greenwich

 

 

Below are the complete example of calculating seconds/minutes/hours/week between two given dates alone with JUtil Testcase.

package com.example1;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Stream;

/**
 * Created by MYPC on 1/15/2017.
 */
public class DateUtils {

    /**
     * Calculated Nos of Days between given two Date.
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long DaysBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.DAYS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of hours between given two Date.
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long HoursBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.HOURS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of Minutes between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long MinsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.MINUTES.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of Seconds between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long SecondsBetween(LocalDateTime startDate, LocalDateTime endDate) {
        return ChronoUnit.SECONDS.between(startDate, endDate);
    }

    /**
     * Calculated Nos. of weeks between given two Date
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long WeeksBetween(LocalDate startDate, LocalDate endDate) {
        return ChronoUnit.WEEKS.between(startDate, endDate);
    }

    /**
     * It will return days between two Dates with excluding given days in ignore list.
     * and return calculated Days between which is not included the end Date.
     * Example :-
     * LocalDate startDate = LocalDate.parse("2017-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * LocalDate endDate = LocalDate.parse("2017-01-15", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
     * System.out.println(DaysBetween(startDate,endDate,Stream.of(DayOfWeek.SATURDAY,DayOfWeek.SUNDAY).collect(Collectors.toList())));
     *
     * @param startDate
     * @param endDate
     * @param skipDays
     * @return
     */
    public static long DaysBetween(LocalDate startDate, LocalDate endDate, List skipDays) {
        return Stream.iterate(startDate, d -> d.plusDays(1))
                .limit(startDate.until(endDate, ChronoUnit.DAYS))
                .filter(d -> !skipDays.contains(d.getDayOfWeek()))
                .count();
    }
    
}

JUnit test

package com.example1;

import org.junit.Assert;
import org.junit.Test;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by MYPC on 1/15/2017.
 */
public class DateUtilsTest {

    LocalDate startDate = LocalDate.of(2017, Month.JANUARY, 01);
    LocalDate endDate = LocalDate.of(2017, Month.JANUARY, 15);

    LocalDateTime startDt = LocalDateTime.now().minusHours(23);
    LocalDateTime endDt = LocalDateTime.now();

    @Test
    public void DaysBetweenDateTest() {
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate), 14);
    }

    @Test
    public void HoursBetweenDateTest() {
        Assert.assertEquals(DateUtils.HoursBetween(startDt, endDt), 23);
    }

    @Test
    public void MinutesBetweenDateTest() {
        Assert.assertEquals(DateUtils.MinsBetween(startDt, endDt), 1380);
    }

    @Test
    public void SecondsBetweenDateTest() {
        Assert.assertEquals(DateUtils.SecondsBetween(startDt, endDt), 82800);
    }

    @Test
    public void WeeksBetweenDateTest() {
        Assert.assertEquals(DateUtils.WeeksBetween(startDate, endDate), 2);
    }

    @Test
    public void DaysBetweenDateByIgnoreSundayAndSaturdayTest() {
        List ignoreDays = Stream.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY).collect(Collectors.toList());
        Assert.assertEquals(DateUtils.DaysBetween(startDate, endDate, ignoreDays), 10);
    }
}

Testcases snapshots here :-

datetimejunit