Jump to content

Effective java: chapter 5 code sample question

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Hiya,

I'm reading the sample chapter from the book "Effective Java" -->http://java.sun.com/...ve/generics.pdf

And i stumbled upon this piece of code:

static <E> E reduce(List<E> list, Function<E> f, E initVal) {
List<E> snapshot;
[B]synchronized(list) {
[/B]snapshot = new ArrayList<E>(list);[B]
}[/B]
E result = initVal;
for (E e : snapshot)
result = f.apply(result, e);
return result;
}
I got absolutely no idea what the bold part is doing there. Does anyone knows the name of such a structure so i can at least google for it?:rolleyes:

#2
bleedy3

bleedy3

    Newbie

  • Members
  • PipPip
  • 26 posts
The "synchronized" keyword means that only one thread can access an object or a method at a time.

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Ahh right, offcourse. I allready saw threads with synchronized but never in such a way, usually a whole method.. Or at least i don't remember seeing it :D

#4
handita

handita

    Newbie

  • Members
  • Pip
  • 7 posts
I'm too still confuse using it

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Making a variable or method 'synchronized' basicly locks it for the first thread that arrives and it unlocks the method or variable when this thread is finished using it.

Imagine the following

public class Account{

  double money;

   //other stuff


  public void transfer(Account accountB, double amount){   

   [COLOR="green"] if(money - amount >0){[/COLOR]

      money -= amount;

      accountB.depostAmount(amount);

    }

  }

}


Now. There are different banks that use this same account. (== different threads)
if this account has 100$. And bank1 does a transfer of 100$. Right when it reached and has done the green line. bank2 does the same transfer. Note that the money from the transfer hasn't changed yet, only the if is checked.
So the second transfer gets to go first and reduces the money to 0. Then the transfer of bank1 continues and the poor person now has -100$ on his account while with this code it shouldn't have been possible.

By using synchronized around the method this would've been avoided as the 2nd bank would have to wait for bank1 to finish the transfer.