Tuesday, 2 August 2022

Jmh: Microbenchmarking with Java

JMH stands for Java Microbenchmark Harness, it is a java library provided by openjdk that ease the benchmarking of Java applications as simple as possible. 

 

What is Microbenchmarking?

Microbenchmarking measures the performance of small piece of code.

 

In this tutorial series, you are going to learn various examples to start with JMH in your bench-marking process.

      Quick guide to JMH benchmarking
      Run benchmarks using JMH runner
      JMH: Configure a Fork with OptionsBuilder
      JMH: Benchmarking modes
      JMH: Specify the time unit to report the results
      JMH: State objects
      Jmh: @Setup, @TearDown fixture methods
      Jmh: be cautious with dead code
      JMH: Get the individual operations cost with @OperationsPerInvocation
      Jmh: @Param: Benchmark with different values
      Run JMH benchmarking from a junit test
      JMH: result format types
      Send the jmh log messages to a file

All the examples of this tutorial can be downloaded from this link.


Previous                                                 Next                                                 Home

Atlas client: add classification to an entity by unique attributes

AtlasClientV2#addClassification() method is used to add classification to an entities by unique attribues.

 

Signature

public void addClassification(ClassificationAssociateRequest request) throws AtlasServiceException

 

Example

ClassificationAssociateRequest classificationAssociateRequest = new ClassificationAssociateRequest();
classificationAssociateRequest.setEntityTypeName("DemoType2");

Map<String, Object> uniqAttributes = new HashMap<>();
uniqAttributes.put("qualifiedName", "AttributeWithListOfStrings_DEMO1");
classificationAssociateRequest.setEntitiesUniqueAttributes(Arrays.asList(uniqAttributes));

AtlasClassification atlasClassification = new AtlasClassification();
atlasClassification.setTypeName("sensitive_data");
atlasClassification.setPropagate(false);

// This is a mandatory attribute for custom classification sensitive_data
atlasClassification.setAttribute("durationInDays", 10);
classificationAssociateRequest.setClassification(atlasClassification);

atlasClient.addClassification(classificationAssociateRequest);

  For example, before running, I do not have any classifications associated with the entity ‘AttributeWithListOfStrings_DEMO1’. After running the application, sensitive_data classification is attached to the entity.


 

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

Define AddClassificationToAnEntityByUniqueAttribute class.

 

AddClassificationToAnEntityByUniqueAttribute.java

package com.sample.app.classifications;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.instance.AtlasClassification;
import org.apache.atlas.model.instance.ClassificationAssociateRequest;

public class AddClassificationToAnEntityByUniqueAttribute {

    public static void main(String[] args) throws AtlasServiceException {
        AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
                new String[] { "admin", "admin" });

        ClassificationAssociateRequest classificationAssociateRequest = new ClassificationAssociateRequest();
        classificationAssociateRequest.setEntityTypeName("DemoType2");

        Map<String, Object> uniqAttributes = new HashMap<>();
        uniqAttributes.put("qualifiedName", "AttributeWithListOfStrings_DEMO1");
        classificationAssociateRequest.setEntitiesUniqueAttributes(Arrays.asList(uniqAttributes));

        AtlasClassification atlasClassification = new AtlasClassification();
        atlasClassification.setTypeName("sensitive_data");
        atlasClassification.setPropagate(false);

        // This is a mandatory attribute for custom classification sensitive_data
        atlasClassification.setAttribute("durationInDays", 10);
        classificationAssociateRequest.setClassification(atlasClassification);

        atlasClient.addClassification(classificationAssociateRequest);

    }

}

After running above application, I can see that ‘sensitive_data’ classification is attached to the entity.





Previous                                                    Next                                                    Home

HIVE: Exploring select statement

For all the examples, I am going to use below table definition.

CREATE TABLE employee (
id INT,
name STRING,
hobbies ARRAY<STRING>,
technology_experience MAP<STRING,STRING>,
gender_age STRUCT<gender:STRING,age:INT>
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '|'
COLLECTION ITEMS TERMINATED BY ','
MAP KEYS TERMINATED BY ':'
STORED AS TEXTFILE;

 

Step 1: Create table employee.

hive> CREATE TABLE employee (
    > id INT,
    > name STRING,
    > hobbies ARRAY<STRING>,
    > technology_experience MAP<STRING,STRING>,
    > gender_age STRUCT<gender:STRING,age:INT>
    > )
    > ROW FORMAT DELIMITED
    > FIELDS TERMINATED BY '|'
    > COLLECTION ITEMS TERMINATED BY ','
    > MAP KEYS TERMINATED BY ':'
    > STORED AS TEXTFILE;
OK
Time taken: 0.034 seconds

 

Step 2: Create empInfo.txt file.

 

empInfo.txt

 

1|Hari|Football,Cricket|Java:3.4Yrs,C:4.5Yrs|Male,30
2|Chamu|Trekking,Watching movies|Selenium:5.6Yrs|Feale,38
3|Sailu|Chess,Listening to music|EmbeddedC:9Yrs|Femle,32
4|Gopi|Cricket|Datastage:11Yrs|Male,32

 

Step 3: Get the actual hdfs content location of table employee table and place empInfo.txt file there.

 

Execute the command ‘describe formatted employee;’ to see the hdfs location.

 

hive> describe formatted employee;
OK
# col_name              data_type               comment             
id                      int                                         
name                    string                                      
hobbies                 array<string>                               
technology_experience   map<string,string>                          
gender_age              struct<gender:string,age:int>                       
         
# Detailed Table Information         
Database:               default                  
OwnerType:              USER                     
Owner:                  krishna                  
CreateTime:             Sat Jan 16 11:58:21 IST 2021     
LastAccessTime:         UNKNOWN                  
Retention:              0                        
Location:               hdfs://localhost:9000/user/hive/warehouse/employee   
Table Type:             MANAGED_TABLE            
Table Parameters:        
    COLUMN_STATS_ACCURATE   {\"BASIC_STATS\":\"true\",\"COLUMN_STATS\":{\"gender_age\":\"true\",\"hobbies\":\"true\",\"id\":\"true\",\"name\":\"true\",\"technology_experience\":\"true\"}}
    bucketing_version       2                   
    numFiles                0                   
    numRows                 0                   
    rawDataSize             0                   
    totalSize               0                   
    transient_lastDdlTime   1610778501          
         
# Storage Information        
SerDe Library:          org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe   
InputFormat:            org.apache.hadoop.mapred.TextInputFormat     
OutputFormat:           org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat   
Compressed:             No                       
Num Buckets:            -1                       
Bucket Columns:         []                       
Sort Columns:           []                       
Storage Desc Params:         
    collection.delim        ,                   
    field.delim             |                   
    mapkey.delim            :                   
    serialization.format    |                   
Time taken: 0.08 seconds, Fetched: 38 row(s)

From the output, I can confirm the content location of employee table as ‘/user/hive/warehouse/employee’.

 

Let’s put empInfo.txt file into the folder ‘/user/hive/warehouse/employee’.

hdfs dfs -put empInfo.txt /user/hive/warehouse/employee.


Query employee table.

hive> select * from employee;
OK
1   Hari    ["Football","Cricket"]  {"Java":"3.4Yrs","C":"4.5Yrs"}  {"gender":"Male","age":30}
2   Chamu   ["Trekking","Watching movies"]  {"Selenium":"5.6Yrs"}   {"gender":"Feale","age":38}
3   Sailu   ["Chess","Listening to music"]  {"EmbeddedC":"9Yrs"}    {"gender":"Femle","age":32}
4   Gopi    ["Cricket"] {"Datastage":"11Yrs"}   {"gender":"Male","age":32}
Time taken: 0.072 seconds, Fet ched: 4 row(s)


 

Previous                                                    Next                                                    Home

Constant folding in Java

Constant folding is a compiler optimization technique, where recognizing and evaluating constant expressions is done at compile time rather than computing them at runtime.

 

For example,

double d1 = (10 * 87.8654 * 123) - 98;

 

Java compiler evaluate the above constant expression while generating the byte code, and interpreted as ‘double d1 = 107976.442;’

 

ConstantFoldingDemo.java

public class ConstantFoldingDemo {

    private static void dummyCalc() {
        double d1 = (10 * 87.8654 * 123) - 98;
        double d2 = (11 * 88.8654 * 124) - 99;
        double d3 = (12 * 89.8654 * 125) - 100;

        System.out.println("d1 : " + d1);
        System.out.println("d2 : " + d2);
        System.out.println("d3 : " + d3);
    }

    public static void main(String[] args) {
        dummyCalc();
    }

}

 

In the above snippet, values of d1, d2 and d3 are evaluated at compile time. To confirm the same, I decompiled the ConstantFoldingDemo.class file, you can observe the findings in following image.



You may like

Interview Questions

How to check two float values equality?

How to check whether a class is loaded or not in Java?

How to get a random element from Set?

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

Monday, 1 August 2022

Atlas Client: add classification to an entities by entity id

AtlasClientV2#addClassification method is used to attach a classification to an entity/entities.

 

Signature

public void addClassification(ClassificationAssociateRequest request)

 

Example

ClassificationAssociateRequest classificationAssociateRequest = new ClassificationAssociateRequest();
classificationAssociateRequest.setEntityGuids(Arrays.asList(entityGuid));

AtlasClassification atlasClassification = new AtlasClassification();
atlasClassification.setTypeName("sensitive_data");
atlasClassification.setPropagate(false);

// This is a mandatory attribute for custom classification sensitive_data
atlasClassification.setAttribute("durationInDays", 10);
classificationAssociateRequest.setClassification(atlasClassification);

atlasClient.addClassification(classificationAssociateRequest);

Find the below working application.

 

Create atlas-application.properties file under src/main/resources folder.

 

atlas-application.properties

atlas.client.readTimeoutMSecs=30000
atlas.client.connectTimeoutMSecs=30000

Define AddClassificationToAnEntity class.

 

AddClassificationToAnEntity.java

package com.sample.app.classifications;

import java.util.Arrays;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.instance.AtlasClassification;
import org.apache.atlas.model.instance.ClassificationAssociateRequest;

public class AddClassificationToAnEntity {

  public static void main(String[] args) throws AtlasServiceException {
    AtlasClientV2 atlasClient = new AtlasClientV2(new String[] { "http://localhost:21000" },
        new String[] { "admin", "admin" });

    String entityGuid = "898c2aa1-d31a-4d0b-a1fd-7a76da6a4071";

    ClassificationAssociateRequest classificationAssociateRequest = new ClassificationAssociateRequest();
    classificationAssociateRequest.setEntityGuids(Arrays.asList(entityGuid));

    AtlasClassification atlasClassification = new AtlasClassification();
    atlasClassification.setTypeName("sensitive_data");
    atlasClassification.setPropagate(false);

    // This is a mandatory attribute for custom classification sensitive_data
    atlasClassification.setAttribute("durationInDays", 10);
    classificationAssociateRequest.setClassification(atlasClassification);

    atlasClient.addClassification(classificationAssociateRequest);

  }

}

Before running the application, entity looks like below.


 

After running the java application, you can see that the classification ‘sensitive_data’ is added to the entity from below image.



 

  

Previous                                                    Next                                                    Home

Hive: Insert struct data using INSERT statement

Step 1: Create employee table.

CREATE TABLE employee (
    id INT,
    name STRING,
    other_info STRUCT<gender:STRING,age:INT>
 )
 STORED AS TEXTFILE;

 

hive> CREATE TABLE employee (
    >     id INT,
    >     name STRING,
    >     other_info STRUCT<gender:STRING,age:INT>
    >  )
    >  STORED AS TEXTFILE;
OK
Time taken: 0.051 seconds
hive> ;
hive> ;
hive> DESC employee;
OK
id                  	int                 	                    
name                	string              	                    
other_info          	struct<gender:string,age:int>	                    
Time taken: 0.042 seconds, Fetched: 3 row(s)

 

Step 2: Insert data into employee table by executing below statement.

hive> INSERT INTO employee SELECT "1","Krishna",NAMED_STRUCT('gender', 'Male', 'age', 32);
Query ID = cloudera_20220419062424_01fbea53-8448-400a-b8cc-a1d23dc19c6f
Total jobs = 3
Launching Job 1 out of 3
Number of reduce tasks is set to 0 since there's no reduce operator
Starting Job = job_1649172504056_0034, Tracking URL = http://quickstart.cloudera:8088/proxy/application_1649172504056_0034/
Kill Command = /usr/lib/hadoop/bin/hadoop job  -kill job_1649172504056_0034
Hadoop job information for Stage-1: number of mappers: 1; number of reducers: 0
2022-04-19 06:24:29,839 Stage-1 map = 0%,  reduce = 0%
2022-04-19 06:24:36,229 Stage-1 map = 100%,  reduce = 0%, Cumulative CPU 1.53 sec
MapReduce Total cumulative CPU time: 1 seconds 530 msec
Ended Job = job_1649172504056_0034
Stage-4 is selected by condition resolver.
Stage-3 is filtered out by condition resolver.
Stage-5 is filtered out by condition resolver.
Moving data to: hdfs://quickstart.cloudera:8020/user/hive/warehouse/employee/.hive-staging_hive_2022-04-19_06-24-22_769_2507653904500688823-1/-ext-10000
Loading data to table default.employee
Table default.employee stats: [numFiles=1, numRows=1, totalSize=18, rawDataSize=17]
MapReduce Jobs Launched: 
Stage-Stage-1: Map: 1   Cumulative CPU: 1.53 sec   HDFS Read: 4198 HDFS Write: 90 SUCCESS
Total MapReduce CPU Time Spent: 1 seconds 530 msec
OK
Time taken: 15.839 seconds

 

Query employee table.

 

Query employee table to confirm the data.

 

hive> SELECT * FROM employee;
OK
1	Krishna	{"gender":"Male","age":32}
Time taken: 0.036 seconds, Fetched: 1 row(s)

 

Previous                                                    Next                                                    Home