Evolutionary High
Evolutionary High

Reputation: 1307

What can be put inside a Synchronized Block?

I know that a block of code or instance can be put into a synchronized block. So consider this short example:

public class SynchronizedObject {   
    public static void main(String args){
        System.out.println(" 1 " );

        synchronized(args){     
            //do stuff  
        }

In this case, the args is an instance am I correct? And this instance is also an object? Under no circumstances can you put variables or local variables into a sync block?

Upvotes: 0

Views: 347

Answers (2)

Sean Landsman
Sean Landsman

Reputation: 7179

In this case args is a local variable - and its an instance of the String class. And String is indeed an Object as all classes in Java are derived from Object

There is no restriction on putting local variables in a sync block - theres not much to gain by doing it, but there are no restrictions on it either.

You dont gain anything useful by synchronizing on a local variable though.

Upvotes: 2

assylias
assylias

Reputation: 328568

Your question is unclear. You seem to mix block and statements:

  • the synchronized block, in your example, is whatever is inside the curly braces, so the //do stuff part.
  • args, in your example, is the lock used by the synchronized statement.

You would probably benefit from reading a tutorial.

What can be put inside a Sychronized Block?

Anything you want as long as it is valid java statements.

the args is an instance am I correct?

args is a reference to an instance of String (although you probably meant String[]).

this instance is also an object?

Well, yes, an instance of a class IS an object.

Under no circumstances can you put variables or local variables into a sync block?

Inside the block, you can do what you want as explained above. The argument to the synchronized keyword (the lock) needs to be a reference to a non null instance of an Object. That could be a local variable if you want (although that will most likely not achieve your goal).

Upvotes: 3

Related Questions