473,395 Members | 2,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Counterpart of the 'synchronized' java keyword?

As far as I understand, 'lock' is the only option, isn't it?

Namely, If I want to declare a 'synchronised' method, I do it this way:

class A {

void AMethod() {
lock (this) {
// the method body
}
}

}

Am I right?

DW
Jun 27 '06 #1
10 2176
DW,

Yes, that is how you do it, although you can choose different objects to
lock on other than "this".

You can also attach the MethodImpl attribute to the method, like so:

class A
{
[MethodImpl(MethodImplOptions.Synchronized)]
void AMethod()
{
}
}

This has the same effect as locking the method on "this".

Hope this helps.

"master" <ma****@master.com> wrote in message
news:OZ**************@TK2MSFTNGP02.phx.gbl...
As far as I understand, 'lock' is the only option, isn't it?

Namely, If I want to declare a 'synchronised' method, I do it this way:

class A {

void AMethod() {
lock (this) {
// the method body
}
}

}

Am I right?

DW

Jun 27 '06 #2
master wrote:
As far as I understand, 'lock' is the only option, isn't it?

Namely, If I want to declare a 'synchronised' method, I do it this way:

class A {

void AMethod() {
lock (this) {
// the method body
}
}

}

Am I right?

DW


Hi DW,

Yes.

--
Hope this helps,
Tom Spink
Jun 27 '06 #3
> You can also attach the MethodImpl attribute to the method, like so:

[MethodImpl(MethodImplOptions.Synchronized)]
void AMethod()


Thanks, I did not know about it.

DW
Jun 27 '06 #4
Hi,

Do not ever lock on 'this', always create an object which is private to
your class, and lock on that.

The reason is that client code may have locked on the instance which
'this' represents, so if you lock on 'this' as well, you'll end up in a
deadlock.

HTH
Andy

master wrote:
You can also attach the MethodImpl attribute to the method, like so:

[MethodImpl(MethodImplOptions.Synchronized)]
void AMethod()


Thanks, I did not know about it.

DW


Jun 27 '06 #5
That's not really an accurate way of indicating why you don't lock on
"this".

While it is true that exposing "this" can contribute to deadlocks, it's
a very small reason. Deadlocks are more an issue that arises when there is
a coupling between objects and the order of operations is not defined
clearly. Deadlocks can certainly arise with using internal objects which
are private as locks. It's not an issue specific to exposing "this".

Ultimately, the reason you do not want to expose "this" is that it is
exposing an implementation detail, which is private. Just like you don't
expose fields which are the backing for properties, you don't expose this.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Andy" <aj*****@alum.rit.edu> wrote in message
news:11**********************@p79g2000cwp.googlegr oups.com...
Hi,

Do not ever lock on 'this', always create an object which is private to
your class, and lock on that.

The reason is that client code may have locked on the instance which
'this' represents, so if you lock on 'this' as well, you'll end up in a
deadlock.

HTH
Andy

master wrote:
> You can also attach the MethodImpl attribute to the method, like
> so:
>
> [MethodImpl(MethodImplOptions.Synchronized)]
> void AMethod()


Thanks, I did not know about it.

DW

Jun 27 '06 #6
'this' is a special keyword which refers to the instance of the class
which is executing the instance code. You can't expose 'this' since
the client already has a reference to the object anyway. So its not
'exposing implementation detail', since the client code has no way of
knowing what you're really locking on (short of decompling your
assembly).

Its true you can have deadlocks within your code without locking on
this; I never said that you couldn't. The point is that you have
control over your own class, and thus know exactly what you're locking
on and can fix it.

What you may not have control over is the client code using your class;
that code may decide to lock on your instance of the object, then call
a method which locks on 'this' That will create a deadlock. This is
especially bad if your code happens to be a library you're selling,
because it will seem as if your library is broken.

You don't have to take my word for it though, this is straight from
MSDN:
"Generally, it is best to avoid locking on a public type, or on object
instances beyond the control of your application. For example,
lock(this) can be problematic if the instance can be accessed publicly,
because code beyond your control may lock on the object as well. This
could create deadlock situations where two or more threads wait for the
release of the same object. Locking on a public data type, as opposed
to an object, can cause problems for the same reason. Locking on
literal strings is especially risky because literal strings are
interned by the common language runtime (CLR). This means that there is
one instance of any given string literal for the entire program, the
exact same object represents the literal in all running application
domains, on all threads. As a result, a lock placed on a string with
the same contents anywhere in the application process locks all
instances of that string in the application. As a result, it is best to
lock a private or protected member that is not interned."

ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.en/dv_csref/html/413e1f28-a2c5-4eec-8338-aa43e7982ff4.htm

No where does it say that locking on this is bad because it exposes
implementation detail (it doesn't, unless the person using your code
figures out why calling certain methods is deadlocking their
application).

Also, please do NOT send me email replies; keep all replies to me on
the thread only.

Thanks
Andy
Nicholas Paldino [.NET/C# MVP] wrote:
That's not really an accurate way of indicating why you don't lock on
"this".

While it is true that exposing "this" can contribute to deadlocks, it's
a very small reason. Deadlocks are more an issue that arises when there is
a coupling between objects and the order of operations is not defined
clearly. Deadlocks can certainly arise with using internal objects which
are private as locks. It's not an issue specific to exposing "this".

Ultimately, the reason you do not want to expose "this" is that it is
exposing an implementation detail, which is private. Just like you don't
expose fields which are the backing for properties, you don't expose this.


Jun 28 '06 #7
>What you may not have control over is the client code using your class;
that code may decide to lock on your instance of the object, then call
a method which locks on 'this' That will create a deadlock.


Not by itself it won't; most common locks are re-entrant, so this will work
fine without deadlocking; you need two threads for a "lock" deadlock to
occur, and (for instance) both threads to be locking on a pair of objects in
a different sequence.

However - to emphasise, I agree 100% with your point: any public class that
locks on "this" is just a ticking bomb, waiting for somebody else to lock on
you. Not to be recommended.

Marc
Jun 28 '06 #8
Then...

Is
[MethodImpl(MethodImplOptions.Synchronized)]
void AMethod()


better than:
[MethodImpl(MethodImplOptions.Synchronized)]
void AMethod() {
lock (<anything>) {
}
}

???

DW
Jun 29 '06 #9
Not better; different; wose in a few cases...

By using [MethodImpl(MethodImplOptions.Synchronized)], you have no control
over what the locking object /is/. Two issues come to mind:

a: you have several disparate methods that do different things; methods A,
B, C lock on X, and D, E lock on Y; you can't do that cleanly with
MethodImpl

b: to avoid deadlocks you need (for instance) to lock on your parent
*before* you lock locally; can't do that with MethodImpl

c: unless you are absolutely sure what the lock object is, you can't use
Monitor.Pulse, Monitor.Wait etc to communicate; if MethodImpl locks against
"this" (and I can't remember, 'cos I don't use
MethodImplOptions.Synchronized), then you might be able to get away with
Pulse(this), but personally I would prefer to be able to /see/ the lock(obj)
statement before I Pulse(obj).

I personally think explicit lock statements are much clearer to follow;
people sometimes say it is more work, which I don't get as
"lock(SyncLock){}" isn't much typing... each to their own.

Marc
Jun 29 '06 #10
I have some problem in understanding what actually lock(something) means.

Does lock(something) {...} mean, that during the execution of {...} any
thread accessing the object something will wait until the block is finished?

For example:

Hashtable ht = new Hashtable();
....
lock ( ht ) {
ht["1"] = "1"; // 1
ht["2"] = "2"; // 2
}

Is it possible for another thread to access ht between the statements 1 and
2 and (for example) determine that it has only one key?

DW

Jun 30 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Frank | last post by:
Hi, In the javadocs regarding many of the java.util classes, it states that the classes are not synchronized, and suggest using the Collections.synchronizedX(...) methods for getting...
7
by: John Thorner | last post by:
Hi, I am creating a new thread for each of the connections to the server: public class Node_C { .... while (listening) { Socket client_socket = server_socket.accept(); Node_CThread node ...
5
by: Max Ischenko | last post by:
Hi, I wrote simple implementation of the "synchronized" methods (a-la Java), could you please check if it is OK: def synchronized(method): """ Guards method execution, similar to Java's...
4
by: Rich Sienkiewicz | last post by:
Some classes, like Queue and SortedList, have a Synchronized method which gives a thread safe wrapper object for these classes. But the lock() statement does the same thing. Is there any rules as to...
1
by: Niklas | last post by:
H What is Java Webstart counterpart in .NET Regard /Niklas
4
by: chrisben | last post by:
Hi I often use Queue.Synchronized method to create a queue for multithread writing. I also know I could use SyncRoot and lock to write Queue. Could anyone here please explain to me the pros and...
8
by: ASP.Net programmer | last post by:
Hi, I have a few methods in a class that I want to synchronize (make sure they can't be used at the same time by multiple threads). As a Java programmer I just do this: public synchronized...
7
by: Alan Wang | last post by:
Hi there, How can I create synchronized method in vb.net like synchronized method in Java? Thanks in advanced Alan
0
by: r035198x | last post by:
Inheritance We have already covered one important concept of object-oriented programming, namely encapsulation, in the previous article. These articles are not articles on object oriented...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.