Results 1 to 8 of 8
Thread: Is this thread safe?
- 07-28-2011, 04:59 PM #1
Member
- Join Date
- Apr 2011
- Posts
- 15
- Rep Power
- 0
Is this thread safe?
Is this implementation thread safe? How do I make it thread safe? It seems to be working when I run it, but I'm not sure if it's correct.
public class Calculate {
private int[] list = {0, 0};
public synchronized String getElements()
{
return list;
}
public synchronized void setElements(int first, int second) {
list[0] = first;
list[1] = second;
}
}
thanksLast edited by veronique; 07-28-2011 at 08:23 PM.
- 07-28-2011, 05:03 PM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
Looks to be.
- 07-28-2011, 05:17 PM #3
Member
- Join Date
- Apr 2011
- Posts
- 15
- Rep Power
- 0
Sorry could you elaborate pls?
- 07-28-2011, 05:22 PM #4
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
As in on what?
You do realise, however, that the Dimension object you return is not thread-safe, however, right? As whoever retrieves it can change its coordinates themselves. You want to return a clone of the Dimension object is you want to prevent that.
- 07-28-2011, 05:26 PM #5
Member
- Join Date
- Apr 2011
- Posts
- 15
- Rep Power
- 0
How would I return a clone? return this.coordinates?
- 07-28-2011, 05:58 PM #6
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 8
As in with the clone method? Or as in creating a new one using the coordinates from the first?
- 07-28-2011, 06:52 PM #7
Member
- Join Date
- Apr 2011
- Posts
- 15
- Rep Power
- 0
using coordinates from the first.
thanks
- 07-28-2011, 07:28 PM #8
The Dimension class has a copy constructor. So instead of returning coordinates, return new Dimension(coordinates).
Get in the habit of using standard Java naming conventions!
Similar Threads
-
A collection is not thread-safe?
By JUser in forum Advanced JavaReplies: 1Last Post: 09-28-2010, 09:38 PM -
Singleton Thread safe class
By userj2ee in forum Advanced JavaReplies: 1Last Post: 08-13-2010, 05:32 PM -
Thread safe without using synchronization
By swetu.vc in forum Threads and SynchronizationReplies: 3Last Post: 01-20-2010, 08:06 AM -
Thread Safe Methods / Locks
By mrhyman in forum Threads and SynchronizationReplies: 16Last Post: 10-24-2008, 09:57 PM -
The safe way to stop a thread
By Java Tip in forum java.langReplies: 0Last Post: 04-09-2008, 06:31 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks