I've got the following question about threads in Java: Isn't there a problem if:
-There's a main program which creates a series of threads. Each thread needs to have access (and to modify) to the same object of a user defined class, and this object has references to a hashtable and a Vector (those are fields of this object)
?

If there's a problem, I'd like some hints to solve it.

Thanks.

Yes, there is a problem, because these threads could potentially access/modify the data at 'unfortunate' times. For example, thread 1 modifies variable A to 2, then thread 2 immediately modifies A to 3 (as a simple but stupid example). Another possibility being that threads 1 and 2 are both using variable A in a series of operations. So both threads want A to maintain some state while they do those operations, but the other threads modifies A, which interferes.

Yes, it is a standard problem. The solutions is called a "lock". Each thread has to get a lock on the object before it modifies it, then releases the lock when its finished. If a thread has already locked the object the second thread must wait until the lock is released. This guarantees that only one tread can modify the object at any one time. Have a little Google for Java threads locks - there's lots of tutorial stuff at every level of detail.

http://java.sun.com/docs/books/tutorial/essential/concurrency/locksync.html

Granted I'm fairly new to Java, but could you not declare variables as synchronized to help solve this problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.