Question about synchronized



Hi,

say I have two different methods M1 and M2 which work on the same object O, whereas M1 is declared 'synchronized' while M2 is not.
Now imagine I start two threads A and B, which keep calling M1 and M2 respectively in an endless loop.


As far as I can tell, if M1 is called by A, a lock is acquired on O and thus each call to M2 in B's context will result in the VM inserting B in the wait set until M1 has finished (this is only because M1 is synchronized).

But what if M2 is called on O in B's context /first/ (remember it's not synchronized), and no lock is acquired on O, and while it's still computing, the VM decides to give A the CPU?
Will M1 now be able to work on O, even though M2 hasn't finished yet?


In other words, is in my case of two functions, two threads and one object the program only thread safe if /both/ methods M1 and M2 are declared synchronized? And what effects could arise from one being not not while the other is?

Thanks,
Matthias
.



Relevant Pages

  • Re: Things to come?
    ... We have had tools stolen from job sites I have worked on ... I can't imagine what it would be like to walk around a corner to nail ... I keep a hardened chain with a security combination lock in the truck ...
    (rec.woodworking)
  • Re: Question about synchronized
    ... VisionSet wrote: ... Now imagine I start two threads A and B, which keep calling M1 and M2 respectively in an endless loop. ... synchronized), and no lock is acquired on O, and while it's still ...
    (comp.lang.java.programmer)
  • Re: wxPython and threading issue
    ... Imagine that it was, say, holding a lock when it was forceably ... The way this was originally working was actually using a subprocess, ...
    (comp.lang.python)
  • Re: smp race fix between invalidate_inode_pages* and do_no_page
    ... do_no_pagedoesn't have a page to lock until it has called ... Imagine the truncate side implemented exactly ... Prev by Date: ...
    (Linux-Kernel)
  • 2.6.19-rc2 cpu hotplug lockdep warning: possible circular locking dependency
    ... Note that this is plain 2.6.19-rc2 (_without_ the slab cpu ... which lock already depends on the new lock. ... Using ACPI for SMP configuration information ... # ACPI Support ...
    (Linux-Kernel)