← Back to Multithreading

Sharing Data Between Threads

Understand how multiple threads can access the same data in a Java application.

1. What Is Shared Data?

Imagine you and your friend are maintaining a notebook.

Both of you can open the same notebook, read its contents, and make changes to it.

The notebook is shared between you.

Something similar can happen in a Java application. Multiple threads can access the same variable or object.

When multiple threads access the same data, we call it shared data.

Let's understand this with a simple Java example.

2. A Simple Example of Sharing Data

Consider the following example.

public class SharedDataExample {

    public static void main(String[] args) {

        int[] counter = {0};

        Thread thread1 = new Thread(() -> {
            counter[0]++;
            System.out.println("Thread 1: " + counter[0]);
        });

        Thread thread2 = new Thread(() -> {
            counter[0]++;
            System.out.println("Thread 2: " + counter[0]);
        });

        thread1.start();
        thread2.start();
    }
}

Let's understand what is happening here.

  1. We create an integer array containing one value: 0.
  2. We create two threads.
  3. Both threads access the same array.
  4. Both threads increase the value stored at position 0.
  5. Both threads print the value.

Notice something important:

We did not create two separate counters. Both threads are working with the same counter.

That is shared data.

The array is being used here simply because it allows both threads to access the same mutable value.

3. Understanding Shared Objects

Shared data does not have to be a simple variable. It can also be an object.

Let's create a small class that stores a counter.

class Counter {

    int value = 0;

    void increment() {
        value++;
    }

    int getValue() {
        return value;
    }
}

Now let's create one Counter object and share it between two threads.

public class SharedObjectExample {

    public static void main(String[] args) {

        Counter counter = new Counter();

        Thread thread1 = new Thread(() -> {
            counter.increment();
            System.out.println(
                "Thread 1: " + counter.getValue()
            );
        });

        Thread thread2 = new Thread(() -> {
            counter.increment();
            System.out.println(
                "Thread 2: " + counter.getValue()
            );
        });

        thread1.start();
        thread2.start();
    }
}

Here, we create only one Counter object.

Both threads receive access to that same object through the counter reference.

They can both call its methods and access its data.

This is another example of sharing data between threads.

4. Shared Data Can Be Read and Modified

When threads share an object or variable, they may perform different operations on it.

For example:

  • One thread may read a value.
  • Another thread may update that value.
  • Multiple threads may try to update the same value.

Let's take a simple example.

class BankAccount {

    int balance = 1000;

    void deposit(int amount) {
        balance = balance + amount;
    }

    int getBalance() {
        return balance;
    }
}

Imagine that two threads are using the same BankAccount object.

One thread deposits money, while another thread checks the account balance.

Both threads are accessing the same account object.

This is a common real-world example of shared data.

5. Is Sharing Data Always a Problem?

No. Sharing data is not automatically a problem.

In fact, sharing data is often necessary when building multithreaded applications.

For example:

  • Multiple threads may access the same customer information.
  • Multiple threads may work with the same shopping cart.
  • Multiple threads may access the same bank account.
  • Multiple threads may update the same application counter.

The important thing is to make sure that shared data is accessed and modified safely.

If multiple threads modify the same data without proper coordination, unexpected results can occur.

We will understand one such problem in our next class.

6. What Did We Learn?

  • Shared data is data that can be accessed by multiple threads.
  • Multiple threads can share the same object.
  • Threads can read and modify shared data.
  • Sharing data is common in real-world applications.
  • Shared data needs to be handled carefully when multiple threads modify it.

Remember: When multiple threads access the same object or variable, they are working with shared data.

Test Your Understanding

Let's check what you have learned in this class.

1. What do we mean by shared data?

2. If two threads use the same Counter object, what are they sharing?

3. Can shared data be an object?

4. Is sharing data between threads always a problem?

5. What can happen when multiple threads modify the same data without proper coordination?

Class Summary

Let's quickly revise what we learned in this class.

  • Shared data is data that multiple threads can access.
  • Multiple threads can access the same object or variable.
  • Threads can read and modify shared data.
  • Sharing data is common in real-world applications.
  • When multiple threads modify shared data, we need to handle it carefully.

We have now understood what shared data means. Next, let's see what can go wrong when multiple threads try to modify the same data.

What's Next?

Class 12: Understanding Race Conditions

Imagine two threads trying to increase the same counter at almost the same time.

You might expect the counter to increase twice. But can the final result sometimes be incorrect?

In the next class, we will understand this problem through a simple counter example and learn what a race condition means.

See you in the next class!

0% Completed

You have completed 11 out of 46 classes.