View Single Post
Old 07-30-2008   #2 (permalink)
Jeroen Mostert


 
 

Re: Use "lock" in three methods to prevent shared-memory corruption

Curious wrote:
Quote:

> I have an arraylist used in three separate methods.
>
> In method #1 (event method), some items are removed from the arraylist
> if certain conditions are met;
>
> In method #2 (event method), properties of some items are modified if
> certain conditions are met;
>
> In method #3, it loops through each item in the arraylist without
> changing any item on the arraylist or removing any item from the
> arraylist. In other words, this is "read-only" type of operation.
>
> Since both #1 and #2 are event methods and may happen anytime, there's
> a chance that #1, #2, and #3 all happen at the same time, then I'll
> run into a memory issue when one process is modifying the arraylist,
> other process(es) are accessing the arraylist.
>
> I plan to use "lock" in all of these three methods. I have questions:
>
> 1) I know "lock" is typically used in two methods. Will there be an
> issue if "lock" is used in more than two methods?
>
No. Locking ensures that only one piece of code can hold the lock at any one
time. It doesn't matter how many threads are trying that simultaneously
(though obviously performance suffers greatly if many threads are contending
for a single lock, but that's another matter altogether).
Quote:

> 2) If I use "lock" in #1 and #2, will locking the process cause the
> associated **event objects** to expire since they are dynamic in
> nature and only live for a very short period of time?
>
What event objects? Neither event handling nor locking intrinsically create
objects.

--
J.
My System SpecsSystem Spec