React: Boost performance with effective rendering

Content posted here with the permission of the author Payal Bhalerao, who is currently employed at Josh Software. Original post available here

We always enjoy fast and responsive user interface, but generally during fast development performance gets neglected. In case of react app development, We generally rely on react’s virtual DOM, that it will perform diffing and re-render only what is changed.

Yes, it does! But why not to give some hints to skip usless re-rendering, if we can!

Let’s try to understand — What are useless re-renderings ?

In many cases, React component will re-render when it doesn’t have to. When result of next rendering would be same as previous, it’s always better to return and render previous output.

For performance optimization, React offers many higher order components and hooks on which we can rely on.

Two of them are— useMemo() & React.memo()

From useMemo() documentation — 
Pass a function and an array of dependenciesuseMemo will only recompute the memoized value when one of the dependencies (either a or b) has changed.

React.useMemo(
  () => computeExpensiveValue(a, b), 
  [a, b]
);

This optimization helps to avoid expensive calculations on every render.

From memo() documentation — 
React.memo is a higher order component. HOC that can optimize rendering of your component given that, it renders the same output with the same properties.

React.memo(function MyComponent(props) {
  /* render using props */
});

Since both terminologies have the word memo it might sound a bit confusing for people. but, it’s all about React optimization and memoization!

“In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.”

Difference between useMemo() and React.memo()

useMemo has a different use case than React.memo. It’s not about preventing an entire component from re-rendering, it’s about simply memoizing some output data. Very unrelated in usage.

The only similarity is that React.memo() and useMemo() both involve “if you see the same inputs as last time, don’t do any extra work – return what you had before”, but React.memo is for wrapping up entire components, and useMemo() is for whatever you want to return from the callback.

In this post, We will discuss React.memo() in detail, how it improves the performance & when to use it.

What is Rect.memo()

React.memo is a higher order component.

It’s similar to React.PureComponent but for functional components instead of classes. If your function component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result.

Let’s take one example,

const Counter = ({counter, value}) => {
    return (
        <div>{counter}: {value}</div>
   )
}
export default Counter;
const App = () => {
    const [count1, setCount1] = React.useState(0)
    const [count2, setCount2] = React.useState(0)

    const incrementCounter1 = () => {
        setCount1(count1 + 1)
    }

    return (
        <>
          <button onClick={incrementCounter1}>
             Increase counter 1
          </button>
          <Counter value={count1} counter={'1'}>Counter1</Counter>
          <Counter value={count2} counter={'2'}>Coutner2</Counter>
          // counter2 component should not re-render, 
          // as we are incrementing only counter1  
        </>
    )
}

Every time we clicks on the button, the state of count1 changes causing the App to re-render both counters which is known as useless re-render. However, we expect only the counter1 to be rendered since nothing has changed with the counter2. In reality, both counters get re-rendered.

How can we address this issue?

React.memo is our answer. All we need to do is to wrap our Counter component within React.memo

export default React.memo(Counter);

By default, React.memo will do shallow comparison of props passed to the component. If these props are unchanged, React.memo will reuse the last rendered result and so it prevents the component from being re-rendered.

How to override default comparison

React.memo accepts a second argument, as a comparison function. This makes it comparable to shouldComponentUpdate in class based components.

React.memo(Component, [areEqual(prevProps, nextProps)]);

The comparison function also returns a boolean value that tells React if it should use the previous result of the component instead of calculating a new one.

  • When true, the function component will not be executed and the previous result will be used instead.
  • When false, the function component will be executed like it normally would.

Watch out! This is the opposite from shouldComponentUpdate!

The comparison function is called with the prevProps and the nextProps. This allows complex logic where the current props are compared to the previous props in order to determine if the output would be different or not, and thus remembered result/memo of the component should be used.

const Counter = ({counter, value}) => {
    return (
        <div>{counter}: {value}</div>
   )
}

const areEqual = (prevProps, nextProps) => {
  return prevProps.counter === nextProps.counter && 
         prevProps.value === nextProps.value;
}
export default React.memo(Counter, areEqual);

Performance-related changes applied incorrectly can even harm performance. so use React.memo() wisely.

When to use React.memo()

Only for functional component and when there is possibility of re-rendering with the same props.

As shallow comparison will use object reference, we should use memo() only when — props are not much nested objects, immutability is maintained for objects which we are passing as props.

When we are passing functions as a props to the component, we should use useCallback, which returns a memoized callback.

useCallback() – This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

When NOT to use React.memo()

If the component doesn’t re-render often with the same props.

With useless props comparison.

When props are multilevel nested objects (without maintaining immutability)

Function as a prop, without memoized callback. (As it’s reference get change every-time)

Conclusion

React.memo() is a great tool to memoize functional components. When applied correctly, it prevents component useless rendering when the next props equal to previous.

Profiler is great dev-tool to find the performance issues and to identify whether we need to optimize the component or not.

Posted in Frontend Development, General, Javascript, React | Tagged , , , , , , | Leave a comment

Improvement Over Android’s Background Processing.

Problems that aroused, since the “Oreo released” –

Whenever we developers needed to execute a long-running operation in the background, we would choose one of the following options :

a) ThreadPools
b) RxJava / Coroutines
c) ForegroundService
d) JobScheduler
e) Alarm Manager + Broadcast receivers

Above options are helpful but sometimes put us in certain situations to write boilerplate code, that should have been handled by the “API / Library itself” (Network Connectivity / Battery Optimization / Memory Availability issues).

Android being a Linux based system it has its own processes to handle like –
a) Scheduling Tasks
b) Memory Management
c) Process Management & so on

As these processes executes, there might come a case where “Android System” may kill / interrupt/ Suspend our Android background thread / background services

Since the release of Oreo , Android has been more focused on battery optimization, memory optimization, user experience. This Restricts developer to perform, background tasks to run only when the application is in foreground or as a foreground service, if in background.

Which some how degrades user experience !

WorkManager For Rescue !

As from the stable release on March 05, 2019 Developers have started using WorkManager features, Soon Developers have come to know what all things can be accomplished without affecting Oreo’s background restrictions on Apps.

WorkManager is intended for tasks that are Deferrable,
i.e not required to run immediately and required to run reliably even for following :

a) App exits
b) Device restarts
c) Network Connectivity Errors
d) Stopped by system (Where we can provide return retry status for the work being processed )


It is an expansion for JobScheduler framework API.
It also lets you observe the state of the work request so that you can update your UI using LiveData.
It also handles Compatibility with different OS versions.
For example, to ensure compatibility back to API level 14, It chooses an appropriate way to schedule a background task depending on the device API level. it might use JobScheduler or a combination of BroadcastReceiver and AlarmManager.

Lets Code

What you’ll learn –
1) Adding WorkManager to your project
2) Adding Work constraints to WorkRequests
3) Scheduling WorkRequest
4) Chaining Multiple WorkRequests

There are a few key WorkManager classes we need to know about –

Worker : Actual work we want to perform in the background.
We need to extend this class and override its doWork() method.

WorkRequest : An actual request object with some work (Worker Object).
We would pass our Worker object, required for creation of our
WorkRequest. While creating “WorkRequest” we can specify things
like Constraints on which the Worker will be running with.

Constraints : A constraints specifies the requirements that need to be met before
WorkRequest be executed. These constraints can be related to
network, battery or storage:

Steps to perform background processing by workManager –
1) Add Dependency
2) Create Worker
3) Set desired Constraints to Worker
4) Is Request Periodic ? if yes –> “PeriodicWorkRequest”
if no –> “OnetimeRequest”, WorkManager Classes.
5) Finally, Schedule it via “WorkManager”.

Adding WorkManager dependency

implementation "android.arch.work:work-runtime:2.2.0" // Current Stable Version

Create a MyWorker class by extending Worker Class –

    class MyWorker(context: Context, workerParams: WorkerParameters) :
        Worker(context, workerParams) {

        override fun doWork(): Result {
            // Define here your work to perform such as
            // Upload images / log files / Rrefresh App config's data periodically

            // Return Result.success() , Result.retry() , Result.failure()  
            return Result.success()
        }
    }

Creating Work Request

// Creating Desired Constraints
// Should run only when device is in charging mode
// should run only connected to network

val constraints:
       Constraints = Constraints.Builder()
                             .setRequiresCharging(true)
                             .setRequiredNetworkType(NetworkType.CONNECTED) 
                                                      .build()

// We can also pass params using WorkerManager's Data Class

val data = Data.Builder()
data.putString("SyncMaster", syncModuleName) 
          
/**        
     if work is periodic 
     (Mostly used for Oreo onward devices due to restriction
      on background services)
*/

var periodicWorkRequest: PeriodicWorkRequest =
                          PeriodicWorkRequest
                            .Builder(MyWorker::class.java,Duration.ofHours(1))
                            .setInputData(data.build())
                            .setConstraints(constraints)
                            .build()

/**
     Else if work is one time task
*/
 
var oneTimeWorkRequest : OneTimeWorkRequest =  
                          OneTimeWorkRequest
                            .Builder(MyWorker::class.java)
                            .setInputData(data.build())
                            .setConstraints(constraints)
                            .build()

/**
    As we have applied the same constraints, both request
    will work only when device is charging or network is connected 
*/   

Scheduling Work –

/**
  Creating a WorkManager object.
  Request can periodicWorkRequest or oneTimeWorkRequest
*/      
 
  WorkManager mWorkManager = WorkManager.getInstance(Context);  
  mWorkManager.enqueue(request); 

Chaining Work –

/**
   Using same WorkManager instance if we need requests to be executed 
   in synchronous fashion, Which can be perform using
*/
              
	        
mWorkManager.beginWith(request1)
            .then(request2)
            .then(request3)
            .then(request4)  
            .enqueue();

 // Requests should be unique either
 // PeriodicWorkRequest  or OneTimeWorkRequest

WorkManager guarantees to schedule requests in a Synchronized manner as specified.
WorkManager will Handle The Rest !!!!!

Posted in Android, General, Mobile Development | Tagged , , , , | Leave a comment

ObjectBox: Alternative to SQLite for android

Content posted here with the permission of the author Krishnakant Kumar, who is currently employed at Josh Software. Original post available here

How many times do we need to write CRUD operation while building android application? Many times right? For me its like daily job.

Till now I used to use sqlite database. But when I came across ObjectBox , I started liking it. Why? Because it saves me a lot of time in writing bucket of code which I used to spend while writing sqlite db query also it was a bit complicated / confusing while reading those queries. While in case of ObjectBox your queries becomes easy and readable.

ObjectBox is open source, NoSql and a super fast mobile database that persists objects. It  avoids many repetitive tasks and offers a simple interface of data. It is used to easily manage app’s data into local storage.

Now let’s look into Core Classes of ObjectBox

MyObjectBox: Generated based on your entity classes, MyObjectBox supplies a builder to set up a BoxStore for your app.

BoxStore: The entry point for using ObjectBox. BoxStore is your direct interface to the database and manages Boxes.

Box: A box persists and queries for entities. For each entity, there is a Box.

Let’s get deeper and see how to integrate it and develop a simple application.

Note: Here I am demonstrating CRUD application using kotlin but its very simple and similar to integrate it with Java.

Add ObjectBox Dependencies

In the project level build.gradle file add the following

buildscript {
    ext.kotlin_version = '1.3.50'
    ext.objectboxVersion = '2.4.0'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "io.objectbox:objectbox-gradle-plugin:$objectboxVersion"
    }
}

Open the build.gradle (Module :App) add the following

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.objectbox'

Now  create the Entity class Notification.kt that contains the properties id, title, and brief and fileSource.

import io.objectbox.annotation.Id
class Notification {
    @Id
    var id: Long = 0
    var title: String? = null
    var brief: String? = null
    var fileSource: String? = null
}

Lets initialize ObjectBoxApp class by extending android Application class and hold the BoxStore.kt reference which will be needed to execute different data CRUD operations. ObjectBoxApp.kt class will look like this :

class ObjectBoxApp : Application(){
    private var boxStore: BoxStore? = null
    override fun onCreate() {
        super.onCreate()
        boxStore = MyObjectBox.builder().androidContext(this@ObjectBoxApp).build()
    }
    fun getBoxStore(): BoxStore? {
        return boxStore
    }
}

Lets set up BoxStore to create a notificationBox.

val boxStore = ((context as MainActivity).application as ObjectBoxApp).getBoxStore()
val notificationBox = boxStore!!.boxFor(Notification::class.java)

Here, Notification is an ObjectBox entity. And now that we have its Box, we can start insert and retrieving data from the database.

Insert data into notification box

var notification = Notification();
notification.title = "5 Key Mobile App Statistics App Developers"
notification.brief = "James Ewen looks at five interesting stats based on data from the last year. Then he's going to attempt to understand what these trends show, how it will affect monetization, engagement and other app metrics."
notificationBox.put(notification)

Get all record

val notificationList = notificationBox.all

For delete notification

val notification = getPlayerById(id)
if (notification != null) {
    notificationBox.remove(id)
}

 

Conclusion:
A simpler way to handle data. It reduces lines of code and avoids query complexity. It is up to 10 times faster than SQLite.

Happy coding. Feedback is most welcome 🙂

Posted in Android, General, Mobile Development, sqlite | Tagged , , , | Leave a comment

Codable — the Swift way

Content posted here with the permission of the author Shirish Bankar, who is currently employed at Josh Software. Original post available here

We have always spent hefty amount of time to parse and format a JSON response to our views and same amount of time again to collect data from there and create a JSON key by key to post to server. It was the traditional way until Apple gave us JSON Codable protocol at WWDC with Swift 4. An elegant way to parse and create JSON to and from models equivalent to the JSON hierarchy.

Swift Codable protocol has offered following things to us :

  • Using Codable, we can model JSONObject or PropertyList file into equivalent Struct or Classes by writing very few lines of code. We don’t have to write the constructor for the properties in the objects. It’s all handed by Codable. We just need to extend our model to conform to the Codable, Decodable or Encodable protocol.
  • Mismatch between the strong data types of Swift and loose data types of JSON has been internally handled by Swift compiler. We can now handle Swift Data types like Date, URL, Float etc
  • Complex JSON can be modelled easily using Nesting Structs for readability.
  • Parsing actual JSON become one-liner using JSONDecoder

For instance we’ll use below JSON :

{
  “username”: “shirish@joshsoftware.com”,
  “id”: 628593,
  “profile_image”: “https: //josh.intranet.com/shirish21790.jpeg", 
  “designation”: “senior ios developer”, 
  “name”: “Shirish Bankar”, 
  “company”:” [“Deskera”, “MangoApps”, “Josh software”]”, 
  “personal_info” : {
  “dob”:”21–07–1990",
  ”blood_group”: ”bpositive”,
  ”marital_status”: ”married”,
  ”contact”: ”8669005821" 
  }
}

Now to parse this JSON we’ll create following struct.

struct EmployeeInfo {
 let username: String?
 let designation: String?
 let id: Int?
 let profile_image: URL?
 let company: [String]?
 let personal_info : PersonalInfo? 
}

Here profile_image is of URL type in our struct and in JSON its a string. Now conforming to Codable protocol will take care of this type mismatch. Here we also have a type PersonalInfo which will become another struct to create a hierarchy and conforming it to Codable will parse data into it too along with EmployeeInfo. Also, notice few constants are declared as camel case which is not Swift standard convention. To take care of camel case we declare CodingKeys enum and tell to use snake case for Swift constant and camel case for JSON. Our final struct will be like :

struct EmployeeInfo: Codable {

    let username: String?
    let designation: String?
    let id: Int?
    let profileImageUrl: URL?
    let company: [String]?
    let personal_info : PersonalInfo?
    
    private enum CodingKeys: String, CodingKey {
        case username 
        case designation
        case id
        case profileImageUrl = "profile_image”
        case avatarUrl = "avatar_url”
        case company
        case personalInfo = "personal_info"
    }
}

Parsing JSON with Codable

guard let apiUrl = URL(string: "https://api.getMyJSON/shirishInfo?") else {
    return
}

URLSession.shared.dataTask(with: apiUrl) {
    (data, response, error) in guard let data = data else{return}

    do {
        let decoder = JSONDecoder()
        let myData = try decoder.decode(EmployeeInfo.self, from: data)
        print(myData.username)
    } catch let err {
        print(“Err”, err)
    } 
}.resume()

We have parsed our JSON data (supposedly) received from the api url. We can access all properties using myData variable.

Now the reverse procedure :-

Creating JSON from your struct :

let encoder = JSONEncoder()encoder.outputFormatting = .prettyPrintedlet data = try encoder.encode(myData)print(String(data: data, encoding: .utf8)!) 
//** This is our json **//

Thats it we can use JSONEncoder to create JSON to be sent to server this easily . So this is the real magic behind Codable .

Posted in General | Leave a comment

Learnings from first solo talk at RubyConf TH

Content posted here with the permission of the author Shweta kale, who is currently employed at Josh Software. Original post available here

I spoke at International RubyConf alone for the first time and it is one of the best experience I ever had at a conference.

It all started few years back when I joined Josh. We had to deliver internal talk and I realised my biggest fear is Public Speaking. I decided to overcome this fear therefore I delivered two talks at RubyConf, first was lightening talk and second talk with a colleague. Now I wanted to move ahead and give solo talk!

I submitted CFP at few of the conferences but it didn’t get selected. I thought it’s not my cup of tea but every time I attend conference the question I used to get from my dad was when are you going to speak at conference? At Josh Software we had a great session on Goal Setting early this year and we all were asked to publish our Goals on internal channel. One of my Goal was to speak at conference and take my parents along with me. Publishing your Goals in your team really helps. Once you publish the Goal you work towards achieving them! I have already achieved 50% of the goals which are supposed to be completed in next 5 years.

In this blog post I will highlight few of the learnings from my first solo talk!

Practise your talk in front of mirror

When you practise your talk in front of mirror you realise what needs to be improved! So always practise your talk in front of mirror.

Record your talk while practising

Recording helps you to analyse your talk on your own! I had recorded my talks 10 times and when I listen first recording and last recoding it had improved a LOT.

Time your talk

Time your talk so you can add/remove few points if required.

Have presenter notes ready

All the tools has facility of presenter notes and when you present your talk you can see those notes on your screen.Those notes are there to give you confidence. I was always worried what if I get blank on the stage? But after adding notes I was bit relaxed as I had feeling that there will be some one who will remind me if I get blank. Though I didn’t use these notes at conference but surely it boosted my confidence!

Check license of the image before you use it

We always tend to add images in our slides because it makes easy to keep audience in sync. But few images are not allowed to be used so always check licence of the image before you use it. Your talk gets recorded so never forget this.

Talk slowly

Talk you are going to deliver is new for most of the people in audience. Audience take some time to figure out what you are talking so talk slowly and repeat your important points twice.

Never read the slides

If you read the slides you loose attention of the audience so never read your slides. Your slides should have highlighted points only. If your slides has more content, audience will start reading it which will distract them.

Look at the audience when you talk

This helps keeping audience engaged in your talk rather than phone 

Make friends before conference start so you have few known faces in the audience

At the time of RubyConf TH There was a cruise dinner arranged at chao phraya river. It was a excellent idea as all speakers got chance to interact with. I knew few of them from DeccanRuby Conf and RubyConf India but many of them were new faces to me but throughout the cruise I didn’t feel like I am new here. Thanks to awesome ruby community. Made some #rubyfriends during this party 

Because of this I had few known faces in the audience which helped me for my own moral support.

Have some punch in first 3 minutes of your talk.

It helps you to get comfortable on stage. In my talk I didn’t have many punches. But when I started the demo of my talk there was laughter and claps from audience at one place. Which gave me some time to cool down and made me comfortable on stage.

Give demo of your talk in front of group of people you are comfortable with, for example meetup

I had given demo of my talk to Josh team. I got really good feedback/ tips from the team also got confidence.

Have backup plan if your laptop crashes

I was all set for my talk and just before I travel my laptop crashed And Apple store said it will take 3-5 days to diagnose the issue. So I had to recreate my presentation. I managed to do it in time. So always keep back up plan ready! Mail slides and PDF to your self and keep it in pen drive.

If you have fear of public speaking start with lightening talk

Many of the conferences has concept of lightening talks. This is a great stage to start with. You get chance to speak in front of many people. Also these talks get recorded. So you can see video later and Enjoy your talk. Also you get chance to learn from mistakes you have made! I had delivered my first lightening talk at DeccanRuby Conf. Timing for these talks are from 3 to 5 minutes.

Don’t give up if talk is not selected

Yes it happens. My 7-8 CFP’s got rejected (different topics) before this selection. But in every conference there are 100’s of CFPs and selection committee has to choose around 10% of the CFPs. There are chances that similar talk was delivered in earlier edition of the conference or there are few better topics than your. So never get disappointed if talk is not selected. Keep trying another conference might be waiting for you!

Submit same talk at multiple conferences

If your talk does not get selected at one conference, it might get selected in other one. I met one person at DeccanRuby Conf whose CFP was not selected at RubyConf TH but got selected in some other conference where mine was not selected. So it totally depends on what kind of topics conference demands.

My first solo talk went well. A lot of people came up to me to say that they liked the talk. It was all very overwhelming. Here are photos with all the attendees.

It was an amazing conference. This was first edition of RubyConf TH – Awesome venue, amazing people, cruise party. Kudos to organisers and volunteers for pulling this off.

You can find slides of the talk here.

Big thanks to Josh team for valuable feedback and conference budget 

🙂

Posted in General | Tagged , , , | Leave a comment

Data Race Detector in Golang

Content written by author Rahul Shewale, who is currently employed at Josh Software.

As we know, Golang is a powerful programming language with built-in concurrency. We can concurrently execute a function with other functions by creating goroutine using go keyword. When multiple goroutines share data or variables, we can face hard to predict race conditions.

In this blog, I am covering following points

  • What is data race condition and how can it occur?
  • How can we detect race conditions?
  • Typical Data Races examples and how can we solve race conditions?

What is the data race condition?
A data race occurs when two goroutines access the same variable concur­rently, and at least one of the accesses is performing a write operation.

Following is a basic example of race condition:

package main
import (
    "fmt"
    "sync"
)
func main() {
    var wg sync.WaitGroup
    wg.Add(5)
    for i := 0; i < 5; i++ {
        go func() {
            fmt.Println(i)
            wg.Done()
        }()
    }
    wg.Wait()
 }
}


In the above example, you must have noticed we have invoked 5 goroutines and access i variable inside the goroutine, but here we faced data race condition because all goroutine read data from i variable concurrently and at the same time for loop write a new value into i variable.

Program OUTPUT:

5 5 5 5 5

How can we detect race conditions?

Now that we know what is a race condition, let’s dive into how to detect these conditions on your Golang project. So Golang provides built-in powerful race detector tools for checking the possible race conditions in program.

To use the built-in race detector you need to simply add -race flag to your go run command:
$ go run -race main.go

This command finds a data race condition in the program if any and print error stack where race condition is occurring

Sample Output
$ go run -race  race_loop_counter.go

==================
WARNING: DATA RACE
Read at 0x00c0000a8020 by goroutine 7:
  main.main.func1()
      /home/-/goworkspace/src/example/race_loop_counter.go:13 +0x3c
Previous write at 0x00c0000a8020 by main goroutine:
  main.main()
      /home/-/goworkspace/src/example/race_loop_counter.go:11 +0xfc
Goroutine 7 (running) created at:
  main.main()
      /home/-/goworkspace/src/example/race_loop_counter.go:12 +0xd8
==================
==================
WARNING: DATA RACE
Read at 0x00c0000a8020 by goroutine 6:
  main.main.func1()

Goroutine 6 (running) created at:
  main.main()
      /home/-/goworkspace/src/example/race_loop_counter.go:12 +0xd8
==================
2 2 4 5 5 Found 2 data race(s)
exit status 66

How can we solve it?

Once you finally find race condition, you will be glad to know that Go offers multiple options to fix it.

Rob Pike has very aptly stated the following phrase. The solution to our problem lies in this simple statement

“Do not communicate by sharing a memory; instead, share memory by communicating.” -Rob Pike

  1. Use Channel for data sharing

Following is a simple program where the goroutine accesses a variable declared in main, increments the same and then closes the wait channel.

Meanwhile, the main thread also attempts to increment the same variable, waits for the channel to close and then prints the variable value.

However, here a race condition in generated between main and goroutine as they both are trying to increment the same variable.

Problem example:

package main
import "fmt"

func main() {
    wait := make(chan int)
    n := 0
    go func() {
        n++
        close(wait)
    }()
    n++
    <-wait
    fmt.Println(n)
}

To solve the above problem we will use the channel.

Solution:

package main
import "fmt"
func main() {
    ch := make(chan int)
    go func() {
        n := 0
        n++
        ch <- n
    }()
    n := <-ch
    n++
    fmt.Println(n)
}

Here the goroutine incrementing the variable and variable value pass through the channel to main function and when channel receives data then main perform next operation.

2) Use sync.Mutex 

Following is a program to get the total number of even and odd numbers from an array of integers, numberCollection and store into a struct.

Following is a program to get the total number of even and odd numbers from an array of integers, numberCollection and store into a struct.

Problem example:
package main
import (
    "fmt"
    "sync"
)

type Counter struct {
    EvenCount int
    OddCount  int
}

var c Counter
func main() {
    numberCollection := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    fmt.Println("Start Goroutine")
    var wg sync.WaitGroup
    wg.Add(11)
    for _, number := range numberCollection {
        go setCounter(&wg, number)
    }
    wg.Wait()
    fmt.Printf("Total Event Number is %v and Odd Number is %v\n", c.EvenCount, c.OddCount)
}
func setCounter(wg *sync.WaitGroup, number int) {
    defer wg.Done()
    if number%2 == 0 {
        c.EvenCount++
        return 
    }
         c.OddCount++
    
}

Output:

 Total Event Number is 5 and Odd Number is 6

If program is checked by race detector flag then we notice line  c.EvenCount++  and line no 31  c.OddCount++ generate race condition because all goroutine writes data into struct object concurrently.

Solution:

To solve this problem, we can use sync.Mutex to lock access to the struct object as in the following example:

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    EvenCount int
    OddCount  int
    mux       sync.Mutex
}

var c Counter

func main() {
    numberCollection := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    fmt.Println("Start Goroutine")
    var wg sync.WaitGroup
    wg.Add(11)
    for _, number := range numberCollection {
        go setCounter(&wg, number)
    }
    wg.Wait()
    fmt.Printf("Total Event Number is %v and Odd Number is %v\n", c.EvenCount, c.OddCount)
}
func setCounter(wg *sync.WaitGroup, number int) {
    defer wg.Done()
    c.mux.Lock()
    defer c.mux.Unlock()
    if number%2 == 0 {
        c.EvenCount++
 return 
    } 
        c.OddCount++
   }

3) Making Copy of variable if Possible 

Problem example:
package main
import (
    "fmt"
    "sync"
)
func main() {
    var wg sync.WaitGroup
    wg.Add(5)
    for i := 0; i < 5; i++ {
        go func() {
            fmt.Printf("%v ", i)
            wg.Done()
        }()
    }
    wg.Wait()
}

In the above problem, we can see five goroutines invoked in for loop and access value of i  from the goroutine. Every Goroutine is called asynchronously and goes to wait state until the for loop is completed or any block operation is created.

After for loop execution is completed all goroutine will start execution and try to access i variable. This will result in a race condition.

For this problem,  we can easily pass copy argument to goroutine and every goroutine gets a copy of the variable. As shown in the example, below we use argument j instead of accessing i from within goroutine.

Solution :

package main
import (
    "fmt"
    "sync"
)
func main() {
    var wg sync.WaitGroup
    wg.Add(5)
    for i := 0; i < 5; i++ {
        go func(j int) {
            fmt.Printf("%v ", j)
            wg.Done()
        }(i)
    }
    wg.Wait()
}

Conclusion:
The preferred way to handle concurrent data access in Go is to use a channel and use -race flag for generating data race report, which helps to avoid a race condition.

Posted in General | Tagged , , , , , , | Leave a comment

Async Action handling in Javascript

Content posted here with the permission of the author Pragati Garud, who is currently employed at Josh Software. Original post available here

As you know javascript is synchronous language. To deal with async operations javascript has provided three ways:
1] Promises
2] Async & await
3] Generator function

Promises: Whenever we ask for some async operation like fetching data from database, instead of waiting for that to get completed, javascript just returns you the promise, on that promise object you can add your success and error handler.

let promise = new Promise((resolve, reject) => {
    // do a thing, if everything is fine then resolve
    // otherwise reject
  })

  //Success handler executed on promise resolve
  promise.then((data) => console.log(data));

  //Error handler executed on promise reject
  promise.catch((error) => console.log(error));

if async operation that you requested is successfully completed then your success handler will get executed otherwise error handler will get executed.

Example: Suppose you want to fetch a list of users from database.(Note: I am assuming that you are aware about the `fetch` function and it’s error handling)

const fetchData = () => {
  fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  })
}

fetchData();

In above code we first requested for users list to server using fetch() and it’s a async operation, so we will get promise as a result of this operation and I added success and error handler on that promise. The response returned by the fetch needs to be converted in the json format.

const fetchData = () => {
  fetch('https://jsonplaceholder.typicode.com/users')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  })
}
fetchData();

here, we called json() on the response to convert that into json, and it is also a async operation that results into a promise. so here from success handler of one promise I am returning another promise called Promise chaining.


So in case of promise chaining, code will look like little bit confusing. hence ES7 comes up with the async/await

Async/Await: async/await is just a syntactical sugar to promise. it provides you the way that you can write your async operations which will look like synchronous. The async function always returns you the promise, even if you return some non-promise value from your async function, javascript just wraps it inside promise and then returns.

async function f() {
  // await works only inside async functions
  let value = await promise;
  return 1;
}

async function f() {
  // await works only inside async functions
  let value = await promise;
  return Promise.resolve(1);
}


await instructs the javascript that wait until provided operation gets finished. The same example that we saw using promises using async/await will be like:

const fetchData = async () => {
  try {
    let apiEndpoint = 'https://jsonplaceholder.typicode.com/users'
    let response = await fetch(apiEndpoint);
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}
fetchData();

here, I defined a async function and used await for my async operations, so javacsript will wait until it will get finished. if your async operation will get failed then await will throw the exception that’s why try catch is used.

Generator Function: It is a special kind of function which can stop it’s execution at a point and resume it’s execution from the same point later. Basically, it’s a function which can pause/resume on our demand.

function* generator() {
   // do something
   yield expression;
}

* after function keyword denotes that it’s a generator function. Inside generator function yield will get used, this is the point where execution of the generator function will get stopped and It will yield an object { value: result, done: true/false } to caller function. value contains the result of the expression given to yield and done indicates that collection on which you are iterating has finished or not(true/false).

Calling a generator function is different than our normal javascript function. Normal function just start it’s execution once we invoke that function. It follows Run to Completion model. But, When we call generator function it does not start the execution of the function body, it just returns you the iterator object on which you can call next() and throw()method. When you call first time next() method on the iterator object then it will start the execution of your function body.

Basic Example for generator:

function* generator() {
   yield 5+3;
   yield 7*2;
}

let it = generator(); // does not start execution of function body
console.log(it.next()); // { value: 8, done: false }
console.log(it.next()); // { value: 14, done: false }
console.log(it.next()); // { value: undefined, done: true }

we can use generator function for async operation handling. we just pause at our async operation and resume generator when that async operation will be done.

Example: fetching list of users from server:

function* fetchData() {
  try {
    let apiEndpoint = 'https://jsonplaceholder.typicode.com/users'
    let response = yield fetch(apiEndpoint);
    let data = yield response.json();
    console.log(data);
  } catch (error) {
    console.log(error);
  }
}

let it = fetchData();

// { value: promise returned by fetch(), done: false }

let promise1 = it.next().value

promise1.then((response) => {
//resume generator by calling next() as your async operation is   fulfilled now.
// we can pass values to generator from here. e.g response is accessible here but we need that in the generator, passed value will gets assign to response variable of the generator.
//{ value: promise returned json(), done: false }  

  let promise2 = it.next(response).value  

  promise2.then((data) => {
    it.next(data);
  });
});

Generator functions are fun and really a good concept. As Generator function provides power to caller to control the execution of the function, most of the libraries uses this concept to handle the async action.

Conclusion:

when to use which one ?

  1. Async/Await – when you want synchronous behaviour with async operations.
  2. Promises – when you want async nature. i.e. execution should continue while you wait for results.
  3. Generators – when you don’t want function to run to completion.

Posted in General | Tagged , , , , | Leave a comment