-1

If I write synchronized(this) in two function of the same java class, but these two functions are maybe called by two threads, does this code still work?

Some fake code maybe looks like:

class A {
        public funA()
            synchronized (this) {
                // do some things here;
            }
        }

        public funB() {
            synchronized (this) {
                // do other things here;
            }
        }
}

Or do I need to add a variable to do it?

2
  • 1
    I don't think it's a duplicate, but it might be considered a "FYI: see also…" Commented Jan 17, 2014 at 21:27
  • @JVMATL considering the OP doesn't seem to understand what the code does, I felt it answered the question. Commented Jan 17, 2014 at 21:35

2 Answers 2

1

What this means is that more than one threads cannot enter these two synchronized blocks (or one of them) at 'the same time'. Whether it works depends on what exactly you want to achieve.

The thread which is currently in such a synchronized block is said to own the object's monitor at that moment of time (in this case the monitor of the object pointed to by this).

Sign up to request clarification or add additional context in comments.

3 Comments

Actually, it doesn't mean that. Some other thread could synchronize on the instance externally and prevent any thread from entering those blocks.
@BrianRoach Actually it means just that. In that case that thread owns the object monitor so 0 threads can enter here (which complies with my statement). I am not commenting here on externally or internally. Each object has exactly one monitor.
I may have been confused by your original wording; this is clearer.
1

The threads are synchronized on this. So only one thread is in the class at the same time (assuming there are no other methods). You are not synchronizing on the methods separately. So this might just work ok. Though it is hard to tell as i have no idea what you want to do in the methods. Concurrency is alway tricky.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.