wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes synchronized classes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "synchronized classes?" Watch "synchronized classes?" New topic
Author

synchronized classes?

Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Can classes be synchronized? I am getting some conflicting information on this from other forums and mock exams. Can anyone please clarify this for me? Also, if interrupt() is used to stop a thread, what method is used to start it again? Do you tell it to run(), or will this restart the thread from the beginning? Thanks for the help!!!

Barry
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1851
section 8.1.2 of the JLS version 2.0 specifies that the
ClassModifier can only be one of
public abstract final
so the matter is closed as to whether classes can be synchronized. Classes cannot be synchronized.

Can anyone please clarify this for me? Also, if interrupt() is used to stop a thread, what method is used to start it again? Do you tell it to run(), or will this restart the thread from the beginning?

suspend, stop and resume methods of the thread class have been deprecated so one cannot use them to do what you want.
I think you can do what you want to do by carefully crafting the loop inside the run method.
example
public void run(){
while (true){
while(Thread.Interrupted(){
\\your programming logic goes here
}
wait()
}
if the thread is interrupted then the thread gets out of the inner loop and then executes the wait method. You can invoke this thread again by saying notifyAll from the controlling thread when you want tho start it again.

------------------
Regds.
Rahul P. Mahindrakar
Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Thanks for the clarification! As to the modifiers, private can also be used in addition to the others you specified, right? Any others?
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1851
No way,
Class modifier can be only public or default not private or protected.

------------------
Regds.
Rahul P. Mahindrakar
Mapraputa Is
Leverager of our synergies
Sheriff

Joined: Aug 26, 2000
Posts: 10065
Barry, what Rahul said about class access modifiers is right - for top-level classes. But for the exam you should remember that if a class is inner, it can be declared as private and protected.
Question "which access modifier can a class have" is not clear until you specify which class do you mean.


Uncontrolled vocabularies
"I try my best to make *all* my posts nice, even when I feel upset" -- Philippe Maquet
Barry Andrews
Ranch Hand

Joined: Sep 05, 2000
Posts: 523

Thanks for the replies!
mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243

You will read statements like "class Vector is synchronized".
What it really means is that all relevent methods( which can corrupt the data inside a Vector )of Vector are declared synchronized. so you need not worry about data corruption when multiple threads are Updating your vectors.
You can also have a synchronized block which may specify any Object ( not a Class ) for obtaining a lock on the Object, say a
TreeSet object.But unless the methods of TreeSet Class are synchronized, obtaining this lock will not help in any way.
Correct me if I am wrong.
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1851
You can also have a synchronized block which may specify any Object ( not a Class ) for obtaining a lock on the Object, say a TreeSet object.But unless the methods of TreeSet Class are synchronized, obtaining this lock will not help in any way.

I disagree on the above statement especially this part.

"But unless the methods of TreeSet Class are synchronized, obtaining this lock will not help in any way.


when trying to add something in a vector you need not lock the vector since the methods are synchronized. However when undertaking operations on the collection classes like ArrayList, etc you need to lock the object in question if you have multithreaded acess to the object in question. Thus if the lock is obtained via a synchronized block on this object it becomes irrelevant if the methods are synchronized or not.
let us consider an object of ArrayList
ArrayList xyz =new ArrayList();
once you lock the object like this
synchronized(xyz){
// xyz is synchronized and locked
}
the effect of the lock exists whether the methods are synchronized or not.
------------------
Regds.
Rahul P. Mahindrakar

[This message has been edited by Rahul Mahindrakar (edited September 27, 2000).]
mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243
probably I was not specific enough:
"You can also have a synchronized block which may specify any Object ( not a Class ) for obtaining a lock on the Object, say a
TreeSet object.But unless the methods of TreeSet Class are synchronized, obtaining this lock will not help in any way."
There are two ways in which one can use synchronized blocks. One is when you use synchronized(this){...} within the class itself,
in which case, this code will be executed only by one thread at a time, and when it is executed, no other synchronized method or block of this class can be executed.
How ever lets say that in class MyClass, i have a following code:
public Vector vec= new Vector();
public void foo(){
String str="xxx";
synchronized(vec){
vec.addElement(str);
String str1 = str;
vec.removeElement(str);
}
}

What I want is that the operation of adding and removing from the vector should be atomic, Meaning that if one thread has added an object to the vector, then another thread should not be able to add or remove any object from it, untill the first thread removes the object it had added.
Will the above synchronized work?
Rahul Mahindrakar
Ranch Hand

Joined: Jul 28, 2000
Posts: 1851
Excellent!! Mohit you are right
"But unless the methods of TreeSet Class are synchronized, obtaining this lock will not help in any way."

I think what you are trying to convey is that if a class x is defined in this way
class x{
public void x(){}
public void y(){}
public void z(){}
}
then when an Object of class x is locked by a synchronized block all the methods are still available to other threads to access. Thus having a lock without having any synchronized methods does not help.
------------------
Regds.
Rahul P. Mahindrakar


[This message has been edited by Rahul Mahindrakar (edited September 29, 2000).]
Jerry Pulley
Ranch Hand

Joined: Sep 19, 2000
Posts: 221
Locking on an object of a class with no synchronized code of its own is actually a common and useful practice. That's why we have two forms of the <code>synchronized</code> keyword. As a method modifier, it's just shorthand for wrapping the entire body of the method within <code>synchronized (this) { ... }</code>, but when used as a statement modifier you can specify any object as the monitor, regardless of whether that object's class has any synchronized code. The effect is that any other statement synchronizing on that object will block until it can obtain that object's lock. Yes, all methods of the "unsynchronized class" can still be called, but that's a far cry from saying that obtaining the lock on such an object is no help.
mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243

So I learnt recently while solving Rob's problem. Thanks Jerry.
However, supposing that you are synchronizing on a ArrayList, so you synchronize the parts of your code where you want the Arraylist to be modified by only one thread at a time. Sure it works fine, but if someone else has an access to that ArrayList, then he might be modifying the ArrayList in his code, out side any synchronized block, without your knowing....Somehow I dont feel very comfortable with the Idea. So do RHE ( although this is an advanced topic).
For that matter you could be synchronizing on a different object X ( which you can create just for the purpose of synchronization, a technique I have seen somewhere)and whereever you want to synchronize on The ArrayList, you could actually synchronize on X, which will work just as fine. However we are using this to mark our access to data which we want to synchronize on. This in itself doesnot ensure that data is safely synchronized in every situation.
Jayashree Ravi
Greenhorn

Joined: Oct 16, 2000
Posts: 7
I have one situation which I am not able to decipher the cource of action the program is taking while doing synchronization. If anyone cud explain me the process it wud be great.
class Thread2 {
static Thread2 Tr3 = new Thread2();
static Thread2 Tr4 = new Thread2();
static Thread Tr1 = new Thread(new Thread1("Tr1"));
//Tr1.setPriority(1);
static Thread Tr2 = new Thread(new Thread1("Tr2"));
//Tr1.setPriority(1);
public static void main (String args[]){
Tr3.somerun(Tr1);
Tr4.somerun(Tr2);
}
public static synchronized void somerun (Thread Tr){
Tr.start();
}
}
class Thread1 implements Runnable{
public String message[] = {"This", "is"," one", "of the Java programs"};
String name;
public Thread1(String id){
name = id;
}
public void run() {
for(int i = 0; i < message.length; i++)
{

System.out.println(name + message[i]);
//randomwait();
}
}
void randomwait(){
try{Thread.currentThread().sleep((long)(3000*Math.random()));}
catch(InterruptedException e){
System.out.println("Interrupted");}
}
}
I have basically tried to synchronized the somerun method. I have instantiated two objects of Thread2 class and tried to run the synchronized method to find out whether the other thread is blocked when the first one is operating. with the statements within the comments block the above program appear to run as expected and that is first Tr3 runs and the Tr4 runs. However if i change the Thread priority to a lower value for both of them then there does not seem tobe any sync at all. also if i add the randomwait() into the run() then also i dont see the effect of sync. can anyone help me?.
Thanks
mohit joshi
Ranch Hand

Joined: Sep 23, 2000
Posts: 243

Continuing with my response to jerry above, I think the issue here is Object Oriented vs. Procedural approach. We can simply extend the rule of Object Oriented Programming : "All data should be accessed only through Class methods" to "All data which needs synchronization should be accessed through Synchronized methods and blocks of the Class and not directly".
Rob Whelan
Ranch Hand

Joined: Oct 18, 2000
Posts: 33
Regarding Jayashree's problem:
The problem you're running into is that the only part you have synchronized is the part where start() is called on those threads. Synchronizing that part only ensures that the threads won't have their start methods called at the same time (which they won't *anyhow* because you're calling start() on both from one thread). Once Tr1 and Tr2 are started, they aren't held by the synchronized block that wraps their start methods.
To see what you're looking for, try synchronizing that run() method.
asteriod
Greenhorn

Joined: Jul 03, 2001
Posts: 2
Originally posted by Rahul Mahindrakar:
[B]section 8.1.2 of the JLS version 2.0 specifies that the
ClassModifier can only be one of
public abstract final
so the matter is closed as to whether classes can be synchronized. Classes cannot be synchronized.
reply by Asteriod :
Classes can be synchronized.

example

public synchronized class HttpPresentationComms {
// fields
public final HttpPresentationRequest request;
public final HttpPresentationResponse response;
public final Application application;
public Session session;
public SessionData sessionData;
public Throwable exception;
public XMLCFactory xmlcFactory;
protected HttpPresentationComms(HttpPresentationRequest p0, HttpPresentationResponse p1, Application p2) {
// CONSTRUCTOR
}
}
Synchronized classes are those whose methods are protected from concurrent invocation of their methods


Love you Hamesha
Marcela Blei
Ranch Hand

Joined: Jun 28, 2000
Posts: 477
"asteriod",
The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements.
Thanks.
jatin rai
Greenhorn

Joined: Dec 27, 2000
Posts: 11
hi!
your problem seems a lil bit complicated as I couldn't figure out why reducing the thread priority messed up the whole code. But where I can help is the other part i.e. random wait. when u synchronised somerun then first tr3 started & initiated tr1. then tr4 started & initiated tr2 (lock was released by tr3 then only tr4 started.). now the lock is just gone, nothing is synchronised. So u can't expect lock behaviour n e more.
As far as somebody above replied that try synchronising run but that also won't helpful b'cos u r overriding run. U should strictly adhere to the signatures of the original run & if u synchronise it most probably your start() won't call run as it usually does although u won't receive n e compile time errors. But i guess u should go & give it a try.
all the best
[This message has been edited by jatin rai (edited July 08, 2001).]
 
 
subject: synchronized classes?