Tuesday, 7 December 2021

volatile reference vs Atomic references defined in java.util.concurrent.atomic package?

What is volatile?

When a variable is defined using volatile modifier, it is guaranteeing that it will not be cached by threads and threads will see the updated value immediately. Without volatile, readers could see some non-updated value.

 

Let’s see it with an example.

VolatileEx.java 

package com.sample.app.threads;

public class VolatileEx extends Thread {
	boolean flag = true;

	public void run() {
		while (flag) {
		}
		System.out.println("Came out of the loop");
	}

	public static void main(String args[]) throws Exception {
		VolatileEx t1 = new VolatileEx();
		t1.start();
		Thread.sleep(1000);
		t1.flag = false;
		System.out.println("Flag is set to " + t1.flag);
	}
}

 

When you ran above application, program goes to infinite loop. Even you set the flag to false, thread keeps using its local copy of the variable flag ( which is true). This problem is solved by volatile keyword.  

 

Define the variable flag using volatile modifier.

volatile boolean flag = true;

 

VolatileEx.java

package com.sample.app.threads;

public class VolatileEx extends Thread {
	volatile boolean flag = true;

	public void run() {
		while (flag) {
		}
		System.out.println("Came out of the loop");
	}

	public static void main(String args[]) throws Exception {
		VolatileEx t1 = new VolatileEx();
		t1.start();
		Thread.sleep(1000);
		t1.flag = false;
		System.out.println("Flag is set to " + t1.flag);
	}
}

 

Output

Came out of the loop
Flag is set to false

Atomic references

java.util.concurrent.atomic package provides a small toolkit of classes that support lock-free thread-safe programming on single variables.

 

From the Java documentation (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/atomic/package-summary.html), I do not see any difference between volatile and atomic references. AtomicReference get and set has the same Java Memory model semantics as a volatile field.

 

If you look at the code of AtomicReference, it internally use a volatile variable.

public class AtomicReference<V> implements java.io.Serializable {

    private volatile V value;

    .......
    .......
}

When to choose what?

If your use case is simple set and get operations, then you can go for volatile modifier. But if you want to have additional CAS (compare-and-swap) functionality, then you can go for atomic references. In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value.

 

CASDemo.java

package com.sample.app.threads;

import java.util.concurrent.atomic.AtomicInteger;

public class CASDemo {
    
    public static void main(String args[]) {
        AtomicInteger atomicInteger = new AtomicInteger(10);
        
        System.out.println("value " + atomicInteger.get());
        
        if(atomicInteger.compareAndSet(10, 21)) {
            System.out.println("\nValue updated successfully!!!!");
            System.out.println("value " + atomicInteger.get());
        }else {
            System.out.println("\nValue is not updated successfully!!!!");
            System.out.println("value " + atomicInteger.get());
        }
        
        if(atomicInteger.compareAndSet(10, 21)) {
            System.out.println("\nValue updated successfully!!!!");
            System.out.println("value " + atomicInteger.get());
        }else {
            System.out.println("\nValue is not updated successfully!!!!");
            System.out.println("value " + atomicInteger.get());
        }
    }

}

Output

value 10

Value updated successfully!!!!
value 21

Value is not updated successfully!!!!
value 21





You may like

Interview Questions

Java: How to replace a value in ArrayList or LinkedList

Why do we declare logger with static and final?

How to check the type of a variable in Java?

Set a system property in command line

How to get the capacity of ArrayList in Java?

Monday, 6 December 2021

FastAPI: Define request sample payload

You can declare an example for a Pydantic model using Config and schema_extra.

 

Let’s it with an example.

class Employee(BaseModel):
    name: str 
    age : int

    class Config:
        schema_extra = {
            "example": {
                "name" : "Krishna",
                "age": 32
            }
        }

 

Find the below working application.

 

requestSamplePayload.py

from fastapi import FastAPI, Body
from pydantic import BaseModel, Field
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32
    }
}

class Employee(BaseModel):
    name: str 
    age : int

    class Config:
        schema_extra = {
            "example": {
                "name" : "Krishna",
                "age": 32
            }
        }

@app.get("/emps")
def allEmployees():
    return emps

@app.post("/emps")
def createEmployee(emp: Employee):
    noOfEmps = len(emps)
    newId = noOfEmps + 1
    emps[newId] = dict(emp)

    return {
        "id" : newId, 
        "name" : emps[newId]['name'], 
        "age": emps[newId]['age']
        }

 

Open terminal and execute the command 'uvicorn requestSamplePayload:app --reload'.

$uvicorn requestSamplePayload:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [48725] using statreload
INFO:     Started server process [48727]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

 

Open the url ‘http://localhost:8000/docs’ in browser and expand ‘POST ​/emps’ api, you will see sample payload for this request.

 


 

 

 

Previous                                                    Next                                                    Home

Spring Data: ArangoTemplate: Replace a document

ArangoTemplate interface provides ‘replace’ method to replace a document.

 

Signature

<T> DocumentEntity replace(Object id, T value, DocumentReplaceOptions options) throws DataAccessException;
<T> DocumentEntity replace(Object id, T value) throws DataAccessException;

 

Replaces the document with id with the one in the body, provided there is such a document and no precondition is violated.

 

‘DocumentReplaceOptions’  is used to provide additional options while replacing the document. Below table summarizes possible options while replacing the document.

 

Option

Data type

Description

waitForSync

Boolean

Wait until document has been synced to disk.

ignoreRevs

Boolean

By default, or if this is set to true, the _rev attributes in the given document is ignored. If this is set to false, then the _rev attribute given in the body document is taken as a precondition. The document is only replaced if the current revision is the one specified.

ifMatch

String

Replace a document based on target revision

returnNew

Boolean

Return additionally the complete new document under the attribute new in the result.

returnOld

Boolean

Return additionally the complete previous revision of the changed document under the attribute old in the result.

silent

Boolean

If set to true, an empty object will be returned as response. No meta-data will be returned for the created document. This option can be used to save some network traffic.

streamTransactionId

String

If set, the operation will be executed within the transaction.

 

Example

 

DocumentReplaceOptions docReplaceOptions = new DocumentReplaceOptions();
docReplaceOptions.returnNew(true);
docReplaceOptions.returnOld(true);

DocumentUpdateEntity updatedDoc = (DocumentUpdateEntity) arangoTemplate.replace(documentCreateEntity1.getId(),emp1ToReplace, docReplaceOptions);

 

Find the below working application.

 

Step 1: Create new maven project ‘arango-template-replace-document’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>arango-template-replace-document</artifactId>
    <version>1</version>

    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-parent -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
    </parent>


    <dependencies>
        <dependency>
            <groupId>com.arangodb</groupId>
            <artifactId>arangodb-spring-boot-starter</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

Step 3: Define entity class.

 

Employee.java

package com.sample.app.entity;

import com.arangodb.springframework.annotation.ArangoId;
import com.arangodb.springframework.annotation.Document;
import org.springframework.data.annotation.Id;

@Document("employees")
public class Employee {

    @Id // db document field: _key
    private String key;

    @ArangoId // db document field: _id
    private String arangoId;

    private Integer id;
    private String firstName;
    private String lastName;
    private Integer age;

    public Employee(Integer id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Employee() {
        
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getArangoId() {
        return arangoId;
    }

    public void setArangoId(String arangoId) {
        this.arangoId = arangoId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee [key=" + key + ", arangoId=" + arangoId + ", id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + ", age=" + age + "]";
    }

}

Step 4: Define Arango DB configuration class.

 

ArangoConfig.java

package com.sample.app.config;

import org.springframework.context.annotation.Configuration;

import com.arangodb.ArangoDB;
import com.arangodb.springframework.annotation.EnableArangoRepositories;
import com.arangodb.springframework.config.ArangoConfiguration;

@Configuration
@EnableArangoRepositories(basePackages = { "com.sample.app" })
public class ArangoConfig implements ArangoConfiguration {

    @Override
    public ArangoDB.Builder arango() {
        return new ArangoDB.Builder().host("localhost", 8529).user("root").password("tiger");
    }

    @Override
    public String database() {
        return "abc_org";
    }
}

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.util.Arrays;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.arangodb.entity.DocumentCreateEntity;
import com.arangodb.entity.DocumentUpdateEntity;
import com.arangodb.entity.MultiDocumentEntity;
import com.arangodb.model.DocumentCreateOptions;
import com.arangodb.model.DocumentReplaceOptions;
import com.arangodb.model.DocumentUpdateOptions;
import com.arangodb.springframework.core.ArangoOperations;
import com.sample.app.entity.Employee;

@SpringBootApplication
public class App {

    @Autowired
    private ArangoOperations arangoTemplate;

    public static void main(String args[]) {
        SpringApplication.run(App.class, args);
    }

    private static void print(DocumentCreateEntity documentCreateEntity) {
        System.out.println("\nid : " + documentCreateEntity.getId());
        System.out.println("key : " + documentCreateEntity.getKey());
        System.out.println("revision : " + documentCreateEntity.getRev());
        System.out.println("doc : " + documentCreateEntity.getNew());
    }

    @Bean
    public CommandLineRunner demo() {

        return (args) -> {
            Employee emp1 = new Employee(1, "Shanmukha Rao", "Kummari");

            DocumentCreateOptions docCreateOptions = new DocumentCreateOptions();
            docCreateOptions.returnNew(true);

            DocumentCreateEntity documentCreateEntity1 = (DocumentCreateEntity) arangoTemplate.insert(emp1,
                    docCreateOptions);

            print(documentCreateEntity1);

            Employee emp1ToReplace = new Employee();
            emp1ToReplace.setKey(documentCreateEntity1.getKey());
            emp1ToReplace.setFirstName("Shanmukha Rao Kummari");
            emp1ToReplace.setAge(35);

            DocumentReplaceOptions docReplaceOptions = new DocumentReplaceOptions();
            docReplaceOptions.returnNew(true);
            docReplaceOptions.returnOld(true);

            DocumentUpdateEntity updatedDoc = (DocumentUpdateEntity) arangoTemplate.replace(documentCreateEntity1.getId(),
                    emp1ToReplace, docReplaceOptions);

            System.out.println("\nUpdated document");
            System.out.println("\nid : " + updatedDoc.getId());
            System.out.println("key : " + updatedDoc.getKey());
            System.out.println("revision : " + updatedDoc.getRev());
            System.out.println("newDoc : " + updatedDoc.getNew());
            System.out.println("oldDoc : " + updatedDoc.getOld());

        };
    }
}

Total project structure looks like below.



Run App.java, you will see below messages in console.

id : employees/37258
key : 37258
revision : _cUlk8nK---
doc : {"_key":"37258","_id":"employees\/37258","_rev":"_cUlk8nK---","id":1,"firstName":"Shanmukha Rao","lastName":"Kummari","_class":"com.sample.app.entity.Employee"}

Updated document

id : employees/37258
key : 37258
revision : _cUlk8p----
newDoc : {"_key":"37258","_id":"employees\/37258","_rev":"_cUlk8p----","firstName":"Shanmukha Rao Kummari","age":35,"_class":"com.sample.app.entity.Employee"}
oldDoc : {"_key":"37258","_id":"employ

You can download complete working application from below link.

https://github.com/harikrishna553/springboot/tree/master/arangodb/arango-template-replace-document


 
 

 


 


 

  

Previous                                                    Next                                                    Home

Java: Implement command line progress bar

Using \r (carriage return), we can implement simple command line progress bar. \r goes back to the start of the same line.

 

ProgressBarDemo.java

import java.util.concurrent.TimeUnit;

public class ProgressBarDemo {

	private static final int TOTAL_CHARS = 50;

	private static String getChars(int noOfChars, String progressChar) {
		StringBuilder builder = new StringBuilder();

		builder.append("Installing");

		for (int i = 0; i < noOfChars; i++) {
			builder.append(progressChar);
		}

		for (int i = noOfChars; i < TOTAL_CHARS; i++) {
			builder.append(" ");
		}

		return builder.toString();

	}

	private static void sleep(int noOfMilliSeconds) {
		try {
			TimeUnit.MILLISECONDS.sleep(noOfMilliSeconds);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void printProgressBar() {
		while (true) {
			for (int i = 1; i < TOTAL_CHARS; i++) {
				System.out.print(getChars(i, "."));
				sleep(300);
				System.out.print("\r");
			}
		}
	}

	public static void main(String[] arg) throws Exception {
		printProgressBar();
	}
}

Output



 

You may like

Miscellaneous