• Post Reply Bookmark Topic Watch Topic
  • New Topic

Making an ArrayList Synchronized  RSS feed

 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I was asked this question in an interview.How can we make an ArrayList synchronized.

I said by doing like this -
public List getList() {
synchronized(myList) {
return new ArrayList(myList);
}
}

Kindly tell me whether i was wrong or right.What are the ways we can make an arraylist synchronized.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose the interviewer was looking for Collections.synchronizedList(theArrayList). Your example sadly doesn't do anything useful.
[ September 13, 2008: Message edited by: Ernest Friedman-Hill ]
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Was I wrong? Can't we do it in the way that i mentioned?
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's not going to work I'm affraid.
I'm guessing they may have been looking for an answer along the lines of retrieving a List instance via Collections.synchronizedList() and taking the measures detailed in the API documentation of that method.

Edit: Ugh, too slow.
[ September 13, 2008: Message edited by: Jelle Klap ]
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok. Sadly , i did not know about it. But good point ..... I got selected.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your solution, only part of the method call is synchronized. The list remains the same, without any synchronization of its own.

Collections.synchronizedList handles that internally. It returns a new List wrapper that is implemented simlarly like this:

Now it uses a specified object as a mutex because of synchronizedMap (it's keySet(), values() and entrySet() methods return different collections that need the same mutex), but for List it's actually the same as this:
 
Patricia Samuel
Ranch Hand
Posts: 300
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for nice explaination
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!