The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A promise is in one of these states:
A pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options happens, the associated handlers queued up by a promise’s then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
As the then() and catch() methods return promises, they can be chained. The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled.
<script> let successAction = new Promise((resolve, reject) => { console.log('Initial'); document.getElementById("promisePending").innerHTML = "Starting..."; // do async action here. setTimeout( function() { let apiResponse = {}; apiResponse.id = 1; apiResponse.name = "Folau"; resolve(apiResponse); document.getElementById("promiseFullFilled").innerHTML = "fullfilled"; }, 3000); }); successAction.then((reponse) => { console.log(reponse); console.log('Do this'); }) .catch((error) => { // This is skiped because resolve is called above. console.error('Error'); console.log(error); }).finally(() => { console.log('finally!'); }); let failedAction = new Promise((resolve, reject) => { console.log('Initial'); document.getElementById("promisePending").innerHTML = "Starting..."; // do async action here. setTimeout( function() { let apiResponse = {}; apiResponse.id = 1; apiResponse.name = "Folau"; reject(apiResponse); document.getElementById("promiseRejected").innerHTML = "rejected"; }, 3000); }); failedAction.then((reponse) => { // This is skiped because reject is called above. console.log(reponse); console.log('Do this'); }) .catch((error) => { console.error('Error'); console.log(error); }).finally(() => { console.log('finally!'); }); </script>
Promise with API HTTP requests
<script> const axiosInstance = axios.create({ baseURL: 'http://localhost:8888', timeout: 1000, headers: { "Content-type": "application/json", "token": "foobar" } }); function getUser(){ console.log("getUser"); let headers = { "Content-Type": "application/json", "token":"lovemesomecoding-token" }; let options = {}; options.method = "GET"; options.headers = headers; let id = 1; let url = "http://localhost:8888/users/"+id; let response = axiosInstance(url, options); response.then(response => { let data = response.data; let content = ""; content += "id: "+data.id+"<br>"; content += "firstName: "+data.firstName+"<br>"; content += "lastName: "+data.lastName+"<br>"; content += "email: "+data.email+"<br>"; document.getElementById("getUserContent").innerHTML = content; }).catch(error => { console.log("error"); let errorResponse = error.response.data; console.log(errorResponse); document.getElementById("errorMsg").innerHTML = errorResponse.message; }); } function updateUser(){ console.log("update user"); let headers = { "Content-Type": "application/json", "token":"lovemesomecoding" }; let user = { firstName: 'Folau', lastName: 'Kaveinga', email: 'folaukaveinga@gmail.com', id: 1 }; let options = {}; options.method = "PUT"; options.body = JSON.stringify(user); options.headers = headers; let url = "http://localhost:8888/users"; let response = axiosInstance(url, options); response.then(response => { let data = response.data; let content = ""; content += "id: "+data.id+"<br>"; content += "firstName: "+data.firstName+"<br>"; content += "lastName: "+data.lastName+"<br>"; content += "email: "+data.email+"<br>"; document.getElementById("updateUserContent").innerHTML = content; document.getElementById("errorMsg").innerHTML = ""; }).catch(error => { console.log("error"); let errorResponse = error.response.data; console.log(errorResponse); document.getElementById("errorMsg").innerHTML = errorResponse.message; }); } </script>
Asnyc/await
The async keyword before a function means that function always returns a promise. Other values are wrapped in a resolved promise automatically.
The await keyword makes JavaScript wait until that promise settles and returns its result.
<div class="row"> <div class="col-1"> </div> <div class="col-4"> Get Average Number <br> <button onclick="getAverageNumber()" type="button" class="btn btn-outline-primary">Get It</button> </div> <div class="col-7" id="averageNum"> </div> </div> <script> /* * Async and await */ async function calculateAverage(num1, num2, num3){ // This could be a REST API call let someNumber = await new Promise(resolve => { setTimeout(() => { resolve(3); }, 2000); }); console.log("num1: "+num1 + ", num2: "+ num2 +", num3: "+ num3 + ", someNumber: "+someNumber); return (num1 + num2 + num3 + someNumber) / 4; } function getAverageNumber(){ calculateAverage(2, 3, 4).then(average => { console.log("average"); console.log(average); document.getElementById("averageNum").innerHTML = average; }); } </script>
ArrayList is a resizable array or dynamic array implementation in java. ArrayList grows dynamically and ensures that there is always a space to add elements. The backing data structure of ArrayList is an array of Object class. ArrayList class in Java has 3 constructors. It has its own version of readObject and writeObject methods. Object Array in ArrayList is transient . It implements RandomAccess, Cloneable, java.io.Serializable.
Internally an ArrayList uses an Object[] Array which is an array of objects. All operation like deleting, adding and updating the elements happens in this Object[] array.
ArrayList is one of the most used data structure in Java today.
ArrayList<String> fruits = new ArrayList<>(2); fruits.add("apple"); fruits.add("banana"); // by adding this, the internal array is doubled it's size fruits.add("cantalope"); System.out.println(fruits.toString());
Array is a fixed size data structure while ArrayList is not. Even if we specify some initial capacity, we can add more elements.
If we try to add an element using the add() method in the array list, Internally it checks for the capacity to store the new element, If the internal array is full then a new capacity(more than old capacity by 50% at least) is calculated and a new array is created and copied over the old array to it.
The time complexity of the common operations in ArrayList java.
Computer random access memory (RAM) is one of the most important components in determining your system’s performance. RAM gives applications a place to store and access data on a short-term basis. It stores the information your computer is actively using so that it can be accessed quickly.
The more programs your system is running, the more you’ll need RAM. The speed and performance of your system directly correlate to the amount of RAM you have installed. If your system has too little RAM, it can be slow and sluggish.
In this article, we are discussing Stack vs Heap which is that Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the RAM.
Memory in a computer is just a sequential set of “buckets” that can contain numbers, characters, or boolean values. By using several buckets in a row, we get arrays. By giving names to a set of contiguous buckets, we get a “structure”. But at its core, a computer memory is a very simple list of numbers. Everything else must be built up upon this.
A stack is a special area of computer’s memory which stores temporary variables created by a function. In stack, variables are declared, stored and initialized during runtime.
It is a temporary storage memory. When the computing task is complete, the memory of the variable will be automatically erased. The stack section mostly contains methods, local variable, and reference variables.
The stack is a LIFO (Last-In-First-Out) data structure. You can view it as a box of perfectly fitted books — the last book you place is the first one you take out. By using this structure, the program can easily manage all its operations and scopes by using two simple operations: push and pop.
These two do exactly the opposite of each other. Push inserts the value to the top of the stack. Pop takes the top value from it.
To keep track of the current memory place, there is a special processor register called Stack Pointer. Every time you need to save something — like a variable or the return address from a function — it pushes and moves the stack pointer up. Every time you exit from a function, it pops everything from the stack pointer until the saved return address from the function. It’s simple!
The heap is a memory used by programming languages to store global variables. By default, all global variable are stored in heap memory space. It supports Dynamic memory allocation.
Heap is created when the JVM starts up and used by the application as long as the application runs. It stores objects and JRE classes. Whenever we create objects it occupies space in the heap memory while the reference of that object creates in the stack. It does not follow any order like the stack. It dynamically handles the memory blocks. It means, we need not to handle the memory manually.
For managing the memory automatically, Java provides the garbage collector that deletes the objects which are no longer being used. Memory allocated to heap lives until any one event, either program terminated or memory free does not occur. The elements are globally accessible in the application. It is a common memory space shared with all the threads. If the heap space is full, it throws the java.lang.OutOfMemoryError.
Parameter | Stack Memory | Heap Space |
---|---|---|
Application | It stores items that have a very short life such as methods, variables, and reference variables of the objects. | It stores objects and Java Runtime Environment (JRE) classes. |
Ordering | It follows the LIFO order. | It does not follow any order because it is a dynamic memory allocation and does not have any fixed pattern for allocation and deallocation of memory blocks. |
Flexibility | It is not flexible because we cannot alter the allocated memory. | It is flexible because we can alter the allocated memory. |
Efficiency | It has faster access, allocation, and deallocation. | It has slower access, allocation, and deallocation. |
Memory Size | It is smaller in size. | It is larger in size. |
Java Options Used | We can increase the stack size by using the JVM option -Xss. | We can increase or decrease the heap memory size by using the –Xmx and -Xms JVM options. |
Visibility or Scope | The variables are visible only to the owner thread. | It is visible to all threads. |
Generation of Space | When a thread is created, the operating system automatically allocates the stack. | To create the heap space for the application, the language first calls the operating system at run time. |
Distribution | Separate stack is created for each object. | It is shared among all the threads. |
Exception Throws | JVM throws the java.lang.StackOverFlowError if the stack size is greater than the limit. To avoid this error, increase the stack size. | JVM throws the java.lang.OutOfMemoryError if the JVM is unable to create a new native method. |
Allocation/ Deallocation | It is done automatically by the compiler. | It is done manually by the programmer. |
Cost | Its cost is less. | Its cost is more in comparison to stack. |
Implementation | Its implementation is hard. | Its implementation is easy. |
Order of allocation | Memory allocation is continuous. | Memory allocated in random order. |
Thread-Safety | It is thread-safe because each thread has its own stack. | It is not thread-safe, so properly synchronization of code is required. |
Array is a data structure that holds a fixed number of values (data points) of the same data type. Each item, or value, is called an element. When we initialize an array, we get to choose what type of data(data type) it can hold and how many elements(length) it can hold.
Each position in the array has an index, starting at 0.
The items in an array are allocated at adjacent(next to each other) memory locations.
By default, an array are filled with default value of its data type once it’s initialized. For example an array of int will have 0 as the default value.
From the above image:
int[] arr = new int[6]; arr[0] = 25; arr[1] = 35; arr[2] = 45; arr[3] = 53; arr[4] = 25; arr[5] = 7; System.out.println("length: " + arr.length); System.out.println(Arrays.toString(arr)); arr = new int[]{25, 35, 45, 53, 25, 7}; System.out.println("length: " + arr.length); System.out.println(Arrays.toString(arr));
length: 6 [25, 35, 45, 53, 25, 7] length: 6 [25, 35, 45, 53, 25, 7]
space | |
---|---|
lookup | |
append(last element) | |
insert | |
delete |
If we want to insert something into an array, first we have to make space by “scooting over” everything starting at the index we’re inserting into.
In the worst case we’re inserting into the 0th index in the array (prepending), so we have to “scoot over” everything in the array. That’s time.
In java
If we want to insert something into an array, first we must have the index or position where the element is going to. Once we have the position, we just set it.
In the worst case the time complexity is time.
Array elements are stored adjacent to each other. So when we remove an element, we have to fill in the gap—”scooting over” all the elements that were after it.
In the worst case we’re deleting the 0th item in the array, so we have to “scoot over” everything else in the array. That’s O(n) time.
Why not just leave the gap? Because the quick lookup power of arrays depends on everything being sequential and uninterrupted. This lets us predict exactly how far from the start of the array the 138th or 9,203rd item is. If there are gaps, we can no longer predict exactly where each array item will be.
In java
If we want to delete an element from an array, first we must have the index or position where the element is in. Once we have the position, we just set it to its data type default value, 0 or null. FYI, there is no Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
In the worst case the time complexity is time.
A pull request is a request asking your upstream project to pull changes into their tree. The request, printed to the standard output, begins with the branch description, summarizes the changes and indicates from where they can be pulled.
The upstream project is expected to have the commit named by <start>
and the output asks it to integrate the changes you made since that commit, up to the commit named by <end>
, by visiting the repository named by <url>
.
git request-pull [-p] <start> <url> [<end>]