Tuesday, March 30, 2021

Java Callable Future

java.util.concurrent.Callable interface similar to Runnable interface to execute a task in multithreaded environment. Callable interface can return any result of type  java.util.concurrent.Future object after completion of a task.  Callable has single call() method similar to run() method of Runnable but has capability to return result.

Future provides get() method to fetch the result of Callable task, its a blocking method, will wait until task completes its execution and return result. Also provides overloaded version of get() method to define the timeout for the task to avoid infinite wait for task to complete.

Also provides cancel() method to cancel the task.

isDone() & isCancelled() provides current status of tasks.


public class Test13 {

public static void main(String args[]) throws InterruptedException, ExecutionException {

List<Future<String>> list = new ArrayList<>();

ExecutorService executor  = Executors.newFixedThreadPool(5);

for(int i=0; i<20; i++) {

Future<String> response=executor.submit(new Test12());

list.add(response);

}

for (Future<String> value : list) {

System.out.println(value.get()+"Thread Name ->"+ Thread.currentThread().getName());

}

executor.shutdown();

}

}


public class Test12 implements Callable<String> {

@Override

public String call() throws Exception {

return "success";

}

}



Labels: , , ,

Sunday, March 21, 2021

Java ConcurrentHashMap

Java ConcurrentHashMap

Introduced in Java 1.5, package java.util.concurrent

Implements ConcurrentMap and Serializable interface. HashMap has performance issue in multithreaded application to overcome this issue ConcurrentHashMap introduced. Operations on this thread safe. ConcurrentHashMap does not allow NULL key or NULL value

You can create a object of ConcurrentHashMap like this

ConcurrentHashMap<K, V> obj = new ConcurrentHashMap<K, V>();

This will create a object with initial capacity 16 which is default.

Default capacity 16 : Its default capacity means can store 16 element when object created with default constructor means no initial capacity provided.

Default concurrency level 16 : Default concurrency level 16 means at a time max 16 threads can perform update operation. There is no lock on read operation.

Default load factor 0.75 : When ConcurrentHashMap size reaches 75 % of  total capacity, it resizes the map.

How ConcurrentHashMap handles multithreading ?

It don't apply lock on whole map instead it divide map into segments / buckets and lock each segments so two  separate thread working on separate segment will not block each other. 

By default it create 16 segments and separate lock for each segment.

Lock will only for write and no lock for read operations.

If one thread is iterating over ConcurrentHashMap and other thread is modifying the structure of ConcurrentHashMap then in this case iteartor will not throw ConcuurentModification exception but this will be the case for  HashMap.








Labels: ,

Wednesday, March 10, 2021

Http idempotent methods

An Http method is idempotent when one or more repetitive request (same request) makes no further impact to server after first request.

Like repetitive GET request makes no impact hence its a idempotent method. The other idempotent methods are PUT and DELETE.

POST is not a idempotent method - First request will insert a record and further same request will add further more records.

PATCH can be idempotent but not necessarily hence it is not safe - It depends upon the implementation, how you are updating the property.


Labels:

Tuesday, March 9, 2021

Http PUT And PATCH

Http PUT:

Use for update the record, if exist update the whole object and if not exist create new object.

Let's say we have employee object with following property

empId

firstName

lastName

department

dob

And if you want to update existing object with new property irrespective of what we have existing value.

In this case you will use PUT method with following

{

"empId":"102",

"firstName":"first",

"lastName":"last",

"department":"computer",

"dob":"2012-10-22"

}

This will overwrite the existing object with new one and if not exist create new one.


Http PATCH:

If you are sure that object exist and you want only update the firstName in this case we will use PATCH method and will pass only property that we want to update

{

"empId":"102",

"firstName":"first"

}

In case object does not exist this operation will fail.

Labels: , , ,

Monday, March 8, 2021

Java equals method and '==' operator

Compare Object value : 

If we want to compare two object value like two Long or Integer value then we must need to use equals method instead of  operator '=='.

Operator  '==' compares reference and not value. But some times this creates an illusion that operator comparing the value. See below example

example: 1

Long l1= 127L;

Long l2=127L;

System.out.println(l1==l2) ///  This will return true;

System.out.println(l1.equals(l2)); ///  This will return true;

But if you give some higher value like;

example: 2

Long l1= 128L;

Long l2=128L;

System.out.println(l1==l2) ///  This will return false;

System.out.println(l1.equals(l2)); ///  This will return true;

example:1 prints true because java maintain Long constant pool for range between -128 to 127.

And when you compared the values above to constant pool range then it given false.

We can compare primitive value using operator '==' but should not be used for object.


Labels: ,