Log in from a computer to take this course

You'll need to log in from a computer to start Learn Intermediate Java. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

Another important scenario when working with multi-threaded programs is managing shared resources between threads.

When you access the same data from two different threads, you may cause a race condition. A race condition occurs when some inconsistency is caused by two threads trying to access the same shared data at the same time.

We can prevent race conditions on shared data using the synchronized keyword in Java. In a threaded program, when you add synchronized to the definition of a function, it will ensure that for a given instance of a class, only one thread can run that method at a time.

Let’s see how we can use thread synchronization to solve a classic race condition problem.

Instructions

1.

Take a look at Counter.java. It is a simple class that should increment a number, and in the main function, we have defined two threads that increment the count one hundred times each.

Underneath where the two threads are defined, write code that will start thread a, start thread b, and then join thread a and thread b back to the main thread.

After you’re done, run the code to see what happens.

2.

Notice something weird? If each thread was supposed to increment the counter 100 times, then the total value of count should have been 200! However, since these two methods were not synchronized, they encountered a race condition. Every time you run this code, you might get a different answer for the final count!

For example, while one thread could be performing .getCount(), another could have performed .setCount(), so the .getCount() would have been operating on outdated information!

The .increment() method is where out Counter performs the calls to .setCount() and .getCount(). Update the method signature to include the synchronized keyword, it goes after the access modifier.

When you’re done, run the code again.

3.

Hurray! You can now see that the counter works as expected, yielding the correct total count for the number of iterations expected. Try adding more threads and validating that it continues to update the count as expected.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?