When to synchronize a list

T

Thomas G. Marshall

Kenneth P. Turvey coughed up:
If you are writing small self contained methods that only do one
thing, this shouldn't matter.


/Often true/, but *not at all true* if you intend this as a strict rule. A
"self contained method", even if very tight, might very well (and often they
do) sensibly contain a few operations in it, some but not all of which need
to be atomic together.

Besides, regardless of quality arguments, the point is that it so often does
matter what precisely gets locked within a method, and if not now, then down
the road. And especially to MT newbies, who whether they believe themselves
to be or not, end up mutexing up the universe in an attempt to get things to
work.
 
H

HalcyonWild

Thomas said:
public void method()
{
synchronized(this)
{
}
}

Instead of the ubiquitous

public synchronized void method()
{
}

For the following reasons:

1. It firms up in their noggins just what object is holding the lock
2. It is only the barest smidgeon slower (I've never met anyone who can
measure it)
3. It allows you (and further maintainers down the road) to easily move
things not requiring protection before and after the lock.

Many times, you'll discover that the vast majority of a synchronized method
does not require the lock at all, which makes #3 above important.

Thanks to all.

Thomas, you are right. Many programmers do not realize that when they
put the synchronized keyword in the method signature, it is the current
instance that is being locked. If you want to synchronize access to the
list, it is the list that should be locked inside the method with
List list = getListFromSomewhere();
synchronized (list)
{
//update list
}
That is, if we assume the list is somewhere else, and not inside the
current class.
Somehow, the synchronized keyword is thought of as the solution to all
multithreading problems. The worst part is that you cannot even easily
spot the bug with testing.

Patricia, I was somewhat unclear with the subject line. When I started
thinking about it, it was about synchronization in Lists, and not
synchronization in general.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top