Results 1 to 4 of 4
Thread: sychronized data type
- 01-19-2009, 01:08 PM #1
Member
- Join Date
- Jan 2009
- Posts
- 6
- Rep Power
- 0
- 01-21-2009, 04:21 PM #2
One way is to mark the field "volatile". However, this does not really accomplish what you want when dealing with a list.
The best way, IMHO, to synchronize an instance field (one defined outside a method) is to create a second field of type Object.
private final Object myFieldSync = new Object();
When you access your field in a way that you need synchronization, wrap the code in a synchronized block.
What I see as the big problem with volatile and the new synchronized wrapper classes is that they don't guarantee you have exclusive use of the object for several statements. That is especially important when dealing with a list object, because a list iterator will throw an exception if the list is modified.Java Code:synchronized(myFieldSync) { \\ do things with myField, this can involve several statements }
- 02-13-2009, 06:39 AM #3
Member
- Join Date
- Oct 2008
- Posts
- 31
- Rep Power
- 0
- 02-13-2009, 08:37 AM #4
Member
- Join Date
- Feb 2009
- Posts
- 7
- Rep Power
- 0
Hello, java girl!
No, there is no generally any way to make a data type synchronized. Synchronizing a complex data type might be very tricky. Anyway there are many basic concurrent data structures (lists, maps, queues, sets, etc) shipped with Java that may suit almost all your needs.
You may check java.util.concurrent package.
You may check java.util.Collections class which has methods:
static List synchronizedList(List list)
static Map synchronizedMap(Map m)
static Set synchronizedSet(Set s)
A good book on concurrency I would always recommend is “Java Concurrency in Practice”.
As for volatile variables they are more about visibility than synchronization. Here is a typical use case for a volatile variable. The code below is wrong:
It may end with infinite loop on some JVMs. That is because ready is nonvolatile.Java Code:public class Test { private static boolean ready; private static class ReaderThread extends Thread { public void run() { while (!ready) doSomeWork(); } private void doSomeWork() { //.... } } public static void main(String[] args) { new ReaderThread().start(); ready = true; } }
Similar Threads
-
error while retrieving data from data base
By kirtesh4u in forum New To JavaReplies: 5Last Post: 11-15-2008, 04:10 PM -
using instanceof to get Object type and parent type?
By xcallmejudasx in forum New To JavaReplies: 2Last Post: 11-06-2008, 06:24 PM -
Data Pipeline 2 - Data Transformation Toolkit for Java Released
By dele in forum Java SoftwareReplies: 0Last Post: 10-31-2008, 02:13 PM -
Data Sorting in a .data file using java
By stutiger99 in forum New To JavaReplies: 2Last Post: 10-08-2008, 02:52 AM -
[SOLVED] Cast string type to int type
By GilaMonster in forum New To JavaReplies: 9Last Post: 09-17-2008, 10:43 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks