473,728 Members | 1,947 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

lock problem

Hi all.
I have an ArrayList and
sometimes while enumerating through, i get an
exception because another thread has added to the ArrayList.
To solve this problem, i lock the enumeration,
passing the ArrayList instance to the lock.
But i still get the same exception.
Thanks for your help.
Sharon.
Nov 16 '05 #1
14 6322

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hernández M.
MCSD

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
Hi all.
I have an ArrayList and
sometimes while enumerating through, i get an
exception because another thread has added to the ArrayList.
To solve this problem, i lock the enumeration,
passing the ArrayList instance to the lock.
But i still get the same exception.
Thanks for your help.
Sharon.

Nov 16 '05 #2
The ArrayList.

"Angel J. Hernández" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hernández M.
MCSD

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
Hi all.
I have an ArrayList and
sometimes while enumerating through, i get an
exception because another thread has added to the ArrayList.
To solve this problem, i lock the enumeration,
passing the ArrayList instance to the lock.
But i still get the same exception.
Thanks for your help.
Sharon.


Nov 16 '05 #3
Try locking the Syncronized ;-)

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:eR******** ******@TK2MSFTN GP10.phx.gbl...
The ArrayList.

"Angel J. Hernández" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hernández M.
MCSD

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
> Hi all.
> I have an ArrayList and
> sometimes while enumerating through, i get an
> exception because another thread has added to the ArrayList.
> To solve this problem, i lock the enumeration,
> passing the ArrayList instance to the lock.
> But i still get the same exception.
> Thanks for your help.
> Sharon.
>
>



Nov 16 '05 #4

"Sharon" <sh****@void.nu ll> wrote in message
news:eR******** ******@TK2MSFTN GP10.phx.gbl...
The ArrayList.


Are the other threads locking the arraylist when they insert items?

Are you maintaining the lock for the duration of the enumeration?

Daviv
Nov 16 '05 #5
Should i try it this way:
lock(ArrayList. Synchronized(ar rayListInstance ))
{
enumerate...
}

And not this way:
lock(arrayListI nstance)
{
enumerate...
}

"Angel J. Hernández" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hernández M.
MCSD

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
Hi all.
I have an ArrayList and
sometimes while enumerating through, i get an
exception because another thread has added to the ArrayList.
To solve this problem, i lock the enumeration,
passing the ArrayList instance to the lock.
But i still get the same exception.
Thanks for your help.
Sharon.


Nov 16 '05 #6
Nop... I owe you an apology. I wrote Syncronized instead of SyncRoot :$

I meant something like this...

ArrayList al = new ArrayList();

lock(al.SyncRoo t) {
foreach(object item in al) {
// Enumerate
}
}
Regards

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:Om******** ******@TK2MSFTN GP09.phx.gbl...
Should i try it this way:
lock(ArrayList. Synchronized(ar rayListInstance ))
{
enumerate...
}

And not this way:
lock(arrayListI nstance)
{
enumerate...
}

"Angel J. Hernández" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hernández M.
MCSD

"Sharon" <sh****@void.nu ll> escribió en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
> Hi all.
> I have an ArrayList and
> sometimes while enumerating through, i get an
> exception because another thread has added to the ArrayList.
> To solve this problem, i lock the enumeration,
> passing the ArrayList instance to the lock.
> But i still get the same exception.
> Thanks for your help.
> Sharon.
>
>



Nov 16 '05 #7
I have to say that I think lock to be maybe the worst named keyword in the language. It gives the impression that it imposes some kind of invisible force field around the object in question that cannot be pierced by other code until the code block executes. This unfortunately is rubbish.

lock(obj)
{
// some thread sensitive code here
}

translates to

Monitor.Enter(o bj);
try
{
// some thread sensitive code here
}
finally
{
Monitor.Exit(ob j);
}

and all Monitor.Enter (simplistically ) does is manipulate the SyncBlock in the objects header. Conceptually It stamps its thread id against the SyncBlock. If another thread id is already stamped there it blocks until the SyncBlock becomes "un-owned" then proceeds to stamp its thread id against the SyncBlock. Monitor.Exit clears the threads id from the syncblock.

So simply stating lock() on anything at all (even if it is the SyncRoot) will achieve nothing UNLESS all code that is accessing the rescource ALSO calls lock on the same thing. In other words

lock(obj)
{
// access some shared. thread sensitive resource
}

only guarantees thread synchronization if all code calls lock(obj), obj being the same physical object as above, before accessing the shared resource.

With collections you can create a thread safe wrapper wound the collection using the Synchronized method - but all this does is do the appropriate locking internally.

One final thing about lock. lock is a block with no timeout. If you get a thread deadlock your application is hosed. The Monitor class also has a TryEnter method which you can pass a timeout to. Ian Griffiths has written a nice wrapper for this which allows you to use stcks based release using the "using" keyword. Heres the URL

http://www.interact-sw.co.uk/iangblo.../03/23/locking

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<ug************ *@tk2msftngp13. phx.gbl>

Nop... I owe you an apology. I wrote Syncronized instead of SyncRoot :$

I meant something like this...

ArrayList al = new ArrayList();

lock(al.SyncRoo t) {
foreach(object item in al) {
// Enumerate
}
}
Regards

"Sharon" <sh****@void.nu ll> escribi? en el mensaje
news:Om******** ******@TK2MSFTN GP09.phx.gbl...
Should i try it this way:
lock(ArrayList. Synchronized(ar rayListInstance ))
{
enumerate...
}

And not this way:
lock(arrayListI nstance)
{
enumerate...
}

"Angel J. Hern?ndez" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hern?ndez M.
MCSD

"Sharon" <sh****@void.nu ll> escribi? en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
> Hi all.
> I have an ArrayList and
> sometimes while enumerating through, i get an
> exception because another thread has added to the ArrayList.
> To solve this problem, i lock the enumeration,
> passing the ArrayList instance to the lock.
> But i still get the same exception.
> Thanks for your help.
> Sharon.
>
>




---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.770 / Virus Database: 517 - Release Date: 27/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]
Nov 16 '05 #8
I realise that my post was incomplete - I didn't address the SyncRoot issue. Take the following code:

static void Main(string[] args)
{
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());

Thread t = new Thread(new ThreadStart(Ouc h));
t.Start();

lock(arr.SyncRo ot)
{
foreach(object o in arr)
{
Thread.Sleep(10 00);
o.ToString();
}
}
}

static void Ouch()
{
Thread.Sleep(10 00);
arr.RemoveAt(0) ;
}

This throws an InvalidOperatio nException because the collection was modified during iteration by the Ouch method running on the other thread. In other words, the SyncRoot is useless on its own in the default case. However, add the following line of code just before the creation of the Thread object (or at least before the thread is started).

arr = ArrayList.Synch ronized(arr);

This creates a thread safe wrapper around the arraylist with operations locking the SyncRoot internally. Now the code will perform correctly as the foreach is synchronized with the modifications.

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<e3************ *@TK2MSFTNGP15. phx.gbl>

I have to say that I think lock to be maybe the worst named keyword in the language. It gives the impression that it imposes some kind of invisible force field around the object in question that cannot be pierced by other code until the code block executes. This unfortunately is rubbish.

lock(obj)
{
// some thread sensitive code here
}

translates to

Monitor.Enter(o bj);
try
{
// some thread sensitive code here
}
finally
{
Monitor.Exit(ob j);
}

and all Monitor.Enter (simplistically ) does is manipulate the SyncBlock in the objects header. Conceptually It stamps its thread id against the SyncBlock. If another thread id is already stamped there it blocks until the SyncBlock becomes "un-owned" then proceeds to stamp its thread id against the SyncBlock. Monitor.Exit clears the threads id from the syncblock.

So simply stating lock() on anything at all (even if it is the SyncRoot) will achieve nothing UNLESS all code that is accessing the rescource ALSO calls lock on the same thing. In other words

lock(obj)
{
// access some shared. thread sensitive resource
}

only guarantees thread synchronization if all code calls lock(obj), obj being the same physical object as above, before accessing the shared resource.

With collections you can create a thread safe wrapper wound the collection using the Synchronized method - but all this does is do the appropriate locking internally.

One final thing about lock. lock is a block with no timeout. If you get a thread deadlock your application is hosed. The Monitor class also has a TryEnter method which you can pass a timeout to. Ian Griffiths has written a nice wrapper for this which allows you to use stcks based release using the "using" keyword. Heres the URL

http://www.interact-sw.co.uk/iangblo.../03/23/locking

Regards

Richard Blewett - DevelopMentor
http://staff.develop.com/richardb/weblog

nntp://news.microsoft. com/microsoft.publi c.dotnet.langua ges.csharp/<ug************ *@tk2msftngp13. phx.gbl>

Nop... I owe you an apology. I wrote Syncronized instead of SyncRoot :$

I meant something like this...

ArrayList al = new ArrayList();

lock(al.SyncRoo t) {
foreach(object item in al) {
// Enumerate
}
}
Regards

"Sharon" <sh****@void.nu ll> escribi? en el mensaje
news:Om******** ******@TK2MSFTN GP09.phx.gbl...
Should i try it this way:
lock(ArrayList. Synchronized(ar rayListInstance ))
{
enumerate...
}

And not this way:
lock(arrayListI nstance)
{
enumerate...
}

"Angel J. Hern?ndez" <an**********@h otmail.com> wrote in message
news:Ob******** ******@TK2MSFTN GP12.phx.gbl...

Are you locking the ArrayList or ArrayList.Syncr onized property?

Regards,
--
Angel J. Hern?ndez M.
MCSD

"Sharon" <sh****@void.nu ll> escribi? en el mensaje
news:%2******** *********@TK2MS FTNGP09.phx.gbl ...
> Hi all.
> I have an ArrayList and
> sometimes while enumerating through, i get an
> exception because another thread has added to the ArrayList.
> To solve this problem, i lock the enumeration,
> passing the ArrayList instance to the lock.
> But i still get the same exception.
> Thanks for your help.
> Sharon.
>
>




---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.770 / Virus Database: 517 - Release Date: 27/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]

---
Incoming mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.770 / Virus Database: 517 - Release Date: 27/09/2004

[microsoft.publi c.dotnet.langua ges.csharp]
Nov 16 '05 #9
Richard Blewett [DevelopMentor] <ri******@devel op.com> wrote:
I realise that my post was incomplete - I didn't address the SyncRoot
issue. Take the following code:

static void Main(string[] args)
{
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());
arr.Add(new object());

Thread t = new Thread(new ThreadStart(Ouc h));
t.Start();

lock(arr.SyncRo ot)
{
foreach(object o in arr)
{
Thread.Sleep(10 00);
o.ToString();
}
}
}

static void Ouch()
{
Thread.Sleep(10 00);
arr.RemoveAt(0) ;
}

This throws an InvalidOperatio nException because the collection was
modified during iteration by the Ouch method running on the other
thread. In other words, the SyncRoot is useless on its own in the
default case. However, add the following line of code just before the
creation of the Thread object (or at least before the thread is
started).

arr = ArrayList.Synch ronized(arr);

This creates a thread safe wrapper around the arraylist with
operations locking the SyncRoot internally. Now the code will perform
correctly as the foreach is synchronized with the modifications.


Note that you don't have to use ArrayList.Synch ronized to use SyncRoot
though - if Ouch() had been written:

static void Ouch()
{
Thread.Sleep(10 00);
lock (arr.SyncRoot)
{
arr.RemoveAt(0) ;
}
}

it would have been fine.

Personally I don't like ArrayList.Synch ronized - I think it's better to
make it obvious when you're locking like this. That's just MHO though.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

2
4469
by: xixi | last post by:
i am using type 4 driver with fp3 on windows 64bit server, auto commit is true, cursor is CS type. i have a sensitive , updatable cursor open and bring back a one row resultset, i get this locklist Lock Name = 0x020027011C0000000000000052 Lock Attributes = 0x00000000 Release Flags = 0x00000002 Lock Count = 1
7
703
by: Sunny | last post by:
Hi, I can not understend completely the lock statement. Actally what is locked: 1. the part of the code between {...} or 2. the object in lock() In the docs is written: for 1: The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a
0
17798
by: Nashat Wanly | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui06032003.asp Don't Lock Type Objects! Why Lock(typeof(ClassName)) or SyncLock GetType(ClassName) Is Bad Rico Mariani, performance architect for the Microsoft® .NET runtime and longtime Microsoft developer, mentioned to Dr. GUI in an e-mail conversation recently that a fairly common practice (and one that's, unfortunately, described in some of our...
14
3837
by: Gary Nelson | last post by:
Anyone have any idea why this code does not work? FileOpen(1, "c:\JUNK\MYTEST.TXT", OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.Shared) Dim X As Integer For X = 1 To 26 FilePut(1, Chr(X + 64)) Next Lock(1, 5, 10)
1
15663
by: charlies224 | last post by:
Hi, I am writting a software that requires me to make sure the Num Lock is always on and Caps Lock is always off. First, I know how to detect if Num Lock or Caps Lock is on or off (if someone is interested, let me know and I will send you the codes). Once we know if the stat of Num Lock/ Caps Lock is not what we desired, we just send the Num Lock / Caps Lock key to change the stat. From most of
2
5863
by: shenanwei | last post by:
DB2 V8.2 on AIX, type II index is created. I see this from deadlock event monitor. 5) Deadlocked Connection ... Participant no.: 2 Lock wait start time: 09/18/2006 23:04:09.911774 ...... Deadlocked Statement: Type : Dynamic Operation: Execute
0
11701
by: cwho.work | last post by:
Hi! We are using apache ibatis with our MySQL 5.0 database (using innodb tables), in our web application running on Tomcat 5. Recently we started getting a number of errors relating to java.sql.SQLException: Deadlock found when trying to get lock; Try restarting transaction message from server: "Lock wait timeout exceeded; try restarting transaction"; We get such errors generally on inserts or updates while applying a
0
3017
by: cburnett | last post by:
Have a peculiar problem regarding lock escalation. Originally lock escalation was occurring because of an application changing most of the rows in a large table. After setting locksize to table to overcome this, still seeing periodic lock escalations (every hour or so) but only of abour 20 rows and for one application at a time. Given a 100MB lock list, why is escalation kicking in and only escalation about 2K of locks? MAXLOCKS would also...
2
2624
by: WingSiu | last post by:
I am writing a Logging util for my ASP.NET application. I am facing mulit process problem. I developed a class LogFactory, and have a method called Get_Logger to create a FileLogger, which will write text into a text file. // sample code FileLogger logger = LogFactory.Get_Logger(); logger.Log("Message here");
0
9277
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9198
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9130
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8129
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4524
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4792
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3236
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2663
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2161
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.