Is the method synchronized when the method is only called in a synchronous redundant block? What happens at the OS level?

Let's say you have a foo () method that is only called in a synchronized block.

Executes method

synchronized void foo() {..}

against just

void foo() {..}

redundant or bad practice, or does it make the method clearer? Does a synchronized keyword in the method signature make the program slower? I am wondering which is better, or if I am missing part of the big picture.

Thank.

+3


source to share


3 answers


This usually means that foo()

it is not the most atomic action, it probably does not preserve invariants, it is only part of the grander timing scheme.

Then he shouldn't announce synchronized

, otherwise the reader may get the wrong idea; and it's a little slower too.

Instead, you could



void foo()
{
    assert Thread.holdsLock(this);
    ...
}

      

it fulfills 2 goals

  • that this method can only be called in an outer block synchonized(this)

  • check this requirement at runtime (I'll include support for all non-production runs)
+1


source


This is not redundant, and in practice it is smart enough to synchronize the locks you are already holding.

APIs that have well-defined boundaries between what's thread safe and what's not easier to work with, and the best boundary is probably at the class level. Thus, if the rest of the class is thread safe and the foo () method is thread safe if synchronized, then you can do that as well and write it in your class. If synchronizing foo () gives you an API with mixed thread-safe and non-thread-safe calls, it will lead to confusion later.



As far as performance goes, I doubt this would be a problem (unprotected locks should have minimal overhead). Get the code working, then see if you need to make it faster.

+1


source


I am assuming your method foo()

is in class A and the caller code (which calls it inside a synchronized block) is in another class B.

My advice is not to do methods A synchronized

, because in single-threaded programs the calls will be systematically slower.

Better to make client classes (like B) do the sync job using sync blocks as you pointed out.

In general, my advice is not to declare a method synchronized because it is more flexible: you can create thread-safe programs using your class with external synchronized blocks, and you can create fast single-threaded applications. You can also warn your users that your class A is not thread safe.

0


source







All Articles