Core Java

Java Concurrency: Synchronized

Previously we had an introduction to threads in Java and some of the internals. On this blog we will proceed on developing thread safe code using synchronized.

Intrinsic lock or monitor lock is achieved using the keyword synchronized

For synchronized we need an object to use for locking. Every object has an intrinsic lock associated with it.

When a thread enters a synchronized block the lock is acquired and once the operation is done the lock will be released.

Let’s start with our application which will be single threaded for start. It will be a counter application.

We will define an interface

package com.gkatzioura.concurrency.intrinsiclock;

public interface Counter {
    void increment();

    Integer get();

}

and a non thread safe implementation

package com.gkatzioura.concurrency.intrinsiclock;

public class SimpleCounter implements Counter {

    private Integer counter = 0;

    @Override
    public void increment() {
        counter++;
    }

    @Override
    public Integer get() {
        return counter;
    }

}

To achieve thread safety we shall use synchronized functions. On synchronized methods the intrinsic lock acquired is the lock of the method’s object. Essentially the lock will be that class instance.
Our class will transform to this.

package com.gkatzioura.concurrency.intrinsiclock;

public class CounterSynchronizedFunctions implements Counter {

    private Integer counter = 0;

    public synchronized void increment() {
        counter++;
    }

    public synchronized Integer get() {
        return counter;
    }

}

Multiple threads will increase the value. If more than two threads increment the same value at the same time we lose increment operations.
Thus we want all threads to increment the counter and not to overwrite each other’s results.
Another thing to observe is that we have synchronized on the get method. This is because we want to get a consistent value. We would like to get a value which has been changed by another thread, this would not be possible if the counter value fetched, would be from the CPU cache and has not been updated with latest changes. By using synchronized in this case we take advantage of the synchronized guarantees. When entering the synchronized block all the variables visible by the thread are updated from the main memory. Also when we leave the synchronized block the variables changes are written back to memory.

Since we put synchronized in the class methods we use the lock of that class instance.
This approach is handy however it has the pitfall that if the same object is used for other locking usages the counter will not operate properly.

Let’s simulate this one.

package com.gkatzioura.concurrency.intrinsiclock;

import java.util.Date;

import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;


@Slf4j
class CounterSynchronizedFunctionsTest {

    @Test
    void name() throws InterruptedException {
        CounterSynchronizedFunctions counter = new CounterSynchronizedFunctions();

        Thread old = new Thread(() -> {
            synchronized (counter) {
                try {
                    log.info("Acquiring lock first [{}]", new Date());
                    Thread.sleep(10000);
                    log.info("Releasing lock [{}]", new Date());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread newOne = new Thread(() -> {
            log.info("I should be blocked [{}]", new Date());
            counter.increment();
            log.info("I am unblocked [{}]", new Date());
        });

        old.start();
        Thread.sleep(1000);
        newOne.start();

        old.join();
        newOne.join();
    }
}

The first thread uses the class instance of Counter as a monitoring lock. The second thread will try to use the increment function and therefore will block, until the lock is released from the first thread.

We can validate by checking the output

12:50:54.631 [Thread-0] INFO com.gkatzioura.concurrency.intrinsiclock.CounterSynchronizedFunctionsTest - Acquiring lock first [Sun Mar 05 12:50:54 GMT 2023]
12:50:55.639 [Thread-1] INFO com.gkatzioura.concurrency.intrinsiclock.CounterSynchronizedFunctionsTest - I should be blocked [Sun Mar 05 12:50:55 GMT 2023]
12:51:04.656 [Thread-0] INFO com.gkatzioura.concurrency.intrinsiclock.CounterSynchronizedFunctionsTest - Releasing lock [Sun Mar 05 12:51:04 GMT 2023]
12:51:04.658 [Thread-1] INFO com.gkatzioura.concurrency.intrinsiclock.CounterSynchronizedFunctionsTest - I am unblocked [Sun Mar 05 12:51:04 GMT 2023]

This is something that can happen since the object can be passed around through the codebase.
To avoid issues like this we will use a lock visible only inside the class.

package com.gkatzioura.concurrency.intrinsiclock;

public class CounterInternallySynchronized implements Counter {

    private static final Object lock = new Object();

    private Integer counter = 0;

    public void increment() {
        synchronized (lock) {
            counter++;
        }
    }

    public Integer get() {
        synchronized (lock) {
            return counter;
        }
    }

}

We can try now the same test but with a different implementation.

package com.gkatzioura.concurrency.intrinsiclock;

import java.util.Date;

import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class CounterInternallySynchronizedTest {

    @Test
    void name() throws InterruptedException {
        Counter counter = new CounterInternallySynchronized();

        Thread old = new Thread(() -> {
            synchronized (counter) {
                try {
                    log.info("Acquiring lock using counter instance [{}]", new Date());
                    Thread.sleep(10000);
                    log.info("Releasing lock using counter instance [{}]", new Date());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread newOne = new Thread(() -> {
            log.info("I should not be blocked [{}]", new Date());
            counter.increment();
            log.info("I finished operation unblocked [{}]", new Date());
        });

        old.start();
        Thread.sleep(1000);
        newOne.start();

        old.join();
        newOne.join();
    }

}
12:52:58.314 [Thread-0] INFO com.gkatzioura.concurrency.intrinsiclock.CounterInternallySynchronizedTest - Acquiring lock using counter instance [Sun Mar 05 12:52:58 GMT 2023]
12:52:59.334 [Thread-1] INFO com.gkatzioura.concurrency.intrinsiclock.CounterInternallySynchronizedTest - I should not be blocked [Sun Mar 05 12:52:59 GMT 2023]
12:52:59.335 [Thread-1] INFO com.gkatzioura.concurrency.intrinsiclock.CounterInternallySynchronizedTest - I finished operation unblocked [Sun Mar 05 12:52:59 GMT 2023]
12:53:08.344 [Thread-0] INFO com.gkatzioura.concurrency.intrinsiclock.CounterInternallySynchronizedTest - Releasing lock using counter instance [Sun Mar 05 12:53:08 GMT 2023]

As expected we keep our code thread safe while we avoid any accidental lock acquisition.

Published on Java Code Geeks with permission by Emmanouil Gkatziouras, partner at our JCG program. See the original article here: Java Concurrency: Synchronized

Opinions expressed by Java Code Geeks contributors are their own.

Emmanouil Gkatziouras

He is a versatile software engineer with experience in a wide variety of applications/services.He is enthusiastic about new projects, embracing new technologies, and getting to know people in the field of software.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button