pkn1230
pkn1230

Reputation: 103

Java code Synchronization issues

I have the following JAVA code that generates a request number based on the maximum request number received from database.

synchronized (this) {
    System.out.println("stsrt");
    certRequest.setRequestNbr(generateRequestNumber(certInsuranceRequestAddRq
                        .getAccountInfo().getAccountNumberId()));
    System.out.println("outside funcvtion"+certRequest.getRequestNbr());
    ItemIdInfo itemIdInfo = new ItemIdInfo();

    dao.insert(certRequest);
    System.out.println("end");
}

To understand the flow I have put System.out.println() statements in my code, the results of which are as follows:

stsrt
stsrt
inside function request number37
outside funcvtion37
inside function request number37
outside funcvtion37
end
end

The "inside function request" depicts my function call generateRequestNumber() which generates the Request number based on database. If you notice the System.out.println() statements, when two threads run at the same time, both enter the Synchronized code together, (as I get the "stsrt" statements together at the beginning), also both the threads exit the code together(as I get the "end" statements together at the end).

Question: How could I synchronize my code so that first one thread completes execution and then another?

Upvotes: 0

Views: 86

Answers (2)

Javy
Javy

Reputation: 964

I doubt, you may create object in every thread, the this represents different object, Hence it can access them in parallel. you can do as the following below

synchronized (this.getClass())

Upvotes: 1

Codebender
Codebender

Reputation: 14471

It depends on what you synchronize with.

When you do synchronized (this) {}, it synchronizes the block with this object. Which means 2 (or more) threads cannot access the block using the same object at the same time.

But in your example, it seems you are using different objects to access the method at the same time. Hence it can access them in parallel.

If you want to synchronize between all the objects, then use a static final Object in your class and synchronize with that object.

Like,

class Test {
    private static final Object obj = new Object();
    public void method() {
        ...
        synchronized(obj) {
            ...
        }
    }
}

Then it will synchronize between all the objects.

Upvotes: 2

Related Questions