Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java synchronized object

farenda 2015-11-09 0

Problem:

How to guarantee thread-safely in concurrent Java code? In this post we’re going to show how to synchronize blocks of code using two different methods.

We are going to continue with the example from the previous post Java synchronized method, where a number of threads were calling dec() method on a Counter to bring it down to zero. Here’s the unsafe class from the previous example:

private static class Counter {
    private int number;

    public Counter(int number) {
        this.number = number;
    }

    public boolean dec() {
        // step 1: comparison
        if (number > 0) {
            // speed up unwanted modifications by other threads:
            Thread.yield();
            // step 2: modification
            --number;
            return true;
        }
        return false;
    }
}

Bad things happen when the Thread Scheduler mix threads between steps 1 and 2. To prevent that we can synchronize access on method level, which we’ve shown in the previous post.

Solution:

In this post we’re going to show how to do synchronized access in two other ways:

  • synchronized(this)
  • synchronized(lockObject).

The first solution is to use synchronize(this) to get the lock of the Counter object, so it’s very similar to what we did in the previous post, when we synchronized on method to get also Counter‘s lock. The difference is that synchronize(this) can be applied on blocks of code within a method, effectively holding lock for less time:

private static class Counter {
    private int number;

    public Counter(int number) {
        this.number = number;
    }

    public boolean dec() {
        // apply lock no block of code:
        synchronized(this) {
            if (number > 0) {
                Thread.yield();
                --number;
                return true;
            }
            return false;
        }
    }
}

In this case it’s almost the same as synchronized on method, because the block spans across whole method. But, of course, there could be more code outside of synchronized block.

In the second solution we use a bit different approach. We create a helper object that we’ll use only for obtaining its lock instead of Counter‘s own lock:

private static class Counter {
    // only for synchronization purposes:
    private final Object lockObject = new Object();

    private int number;

    public Counter(int number) {
        this.number = number;
    }

    public boolean dec() {
        synchronized(lockObject) {
            if (number > 0) {
                Thread.yield();
                --number;
                return true;
            }
            return false;
        }
    }
}

This solution looks similar to synchronized(this), because allows to obtain lock for blocks of code. The difference is that this lock cannot be obtained from outside of this class – for example by subclasses, or clients of the class – preventing denial-of-service attack (public lock could be held by prolonged period of time).

Share with the World!
Categories Java Tags java, java-concurrency
Previous: Java synchronized method
Next: Java synchronize static

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored