Jsp's and synchronization

Hi,

I’m having trouble understanding synchronization in the context of a simple jsp I’ve been experimenting with. My jsp creates a User object:

User user = new User(firstname, lastname, emailAddress);

User and UserIO(below) are imported with the jsp page directive:

<%@ page import=“murachs.secondJSP.*” %>

After creating the User object, the jsp writes the user data to a .txt file using a static method of the UserIO class:

UserIO.saveToFile(user, “C:\\jakarta-tomcat-5.5.9\\webapps\\ROOT\\WEB-INF\\etc\\ estData.txt”);

If the static method saveToFile() is declared with the synchronized keyword, how are two User objects prevented from writing to the file at the same time? It’s my understanding that for every user that accesses the jsp, java creates a new thread, and each thread gets copies of the variables and methods declared in the jsp. However, my book says if you use a jsp page declaration to create a UserIO object like this:

<%!
UserIO out = new UserIO(filename);
%>

then all the users share the one UserIO object. With that setup, it makes sense to me that if the saveToFile() method is synchronized, then the UserIO object would get locked by one thread and prevent other threads from using it to write to the file at the same time. But, in my original situation, I am not creating a UserIO object which all the users share–I’m just calling a static method of UserIO. So, what get’s locked in that situation, i.e. when there is no UserIO object to lock?

WOAH, now hold one there buddy!

Static? In a web context? NO NO NO… man that can really foul things up when multiple users can access it… static is the kiss of DEATH for any web application! Absolutely one of the worse things you can do. Remember static means the is ONLY one and everyone shares the same one… you might want to rethink that…

OK, on to synchronized. It means only one thread may be within the block at any given time, another thread may not enter until the first leaves. Using Synchronized on a method can slow things down to a CRAWL on a website but there are times when its vital. I see where youre going with it (protecting the static method from multiple threads) but Im not 100% sure this is the right way to do it…

Anyway … when using synchronized its better to use a block than do it to a method. The synchronized block should be kept as small as possible, only protecting the vital code. To do a syncronized block the syntax is this:

synchronized (this) {
// code to be protected
}

the this thats passed to the block is nothing more than the current object. You can pass another object to it but this is a very common way to do it… its only because the method requires an object to be passed to it.

so if youre writing to file you can wrap that code within the block, once one thread leaves another may enter … but again YOU HAVE TO BE CAREFUL … this can create bottlenecks like you wouldnt believe

OK, now onto the context of a servlet / jsp (remember a jsp is compiled into a servlet the 1st time it is run) … there is only ONE instance of a servlet at any given time. Each user has their own thread, not instance. It is loaded into the servlet container the first time it is run… everyone shares the same servlet (IE: same JSP) BUT when you create objects everyone gets their own instance of THOSE objects (again when NOT using static) …

BTW, just a quick note here too … you can also implement the SingleThreadedModel interface on a servlet which locks it down like a synchronized block but MAN OH MAN can it slow things down… I dont recommend using it but it is there for any time you have no choice

and one last thing, being as how servlets are always mutlithreaded (unless implementing the SingleThreadedModel interface) you have to remember they are NOT thread safe… you’ll find some people who say anything within a doPost or doGet is thread safe … total CRAP and Ive seen how bad it can get with my own eyes!

Hi,

Thanks for the response.

Remember static means the is ONLY one and everyone shares the same one… you might want to rethink that…

That is an example out of my “Murach’s Servlets and JSP” book(that I ordered used from amazon and waited a month for it to arrive, but the seller stiffed me, so amazon gave me my money back, and then I went to the bookstore and bought it.) But, I think the whole point is that there should be only one object that can write to the file–otherwise the different threads created by multiple users could all write to the file at once and create a mess.

Anyway … when using synchronized its better to use a block than do it to a method.

I’m using a synchronized block for some other statements in the jsp, but I don’t see your point about not using a sychronized method. What’s the difference between declaring a synchronized method, and declaring a regular method and then putting it in a synchronized block? Well, I can think of one difference: other synchronized methods in UserIO would not be put in locked mode.

and one last thing, being as how servlets are always mutlithreaded (unless implementing the SingleThreadedModel interface) you have to remember they are NOT thread safe.

Yes, from what I can tell, that is the point of the exercise: to make the jsp that writes to the database thread safe.

The point is simple … you dont want to lock down that whole method to one thread at a time! You may not see it right now but locking down a method with synchronized will cause a bottleneck in your app that could literally bring the server to its knees!

You have to really think “what if” in this case… Im going thru it right now with a big web app … if you have 100,000 people using an app (hence 100,00 threads) and each one has to wait its turn thru a entire method thats locked down you have a site that becomes the “crawl of death”… In this case think of your synchronized method as a cue, with every thread “lining up” for its turn … just like waiting to get on the highway it can be a real pain.

Now in this case you can have even more problems cause there’s a major issue with any IO in Java … Its threads can be blocked quite easily. Thats one of the reasons you dont use multiple out.printlns in a web app … IO threads CAN and WILL get blocked from time to time. So what happens to your app if the IO thread gets blocked and you have everything synchronized … HMM? Can you say EVERYONE STOP?

and Im sorry but I really have to question ANY Java web app book thats using a static class for reading and writing! Just not a great idea in my opinion! But on the other hand I really dont consider it a real world example because how many times would you allow writing to a single file by multiple users. With a db you really dont have these issues.

With a db you really dont have these issues.

Ok. Thanks.

The point is simple … you dont want to lock down that whole method to one thread at a time!

You said to use a synchronized block instead. I don’t see how putting a method inside a synchronized block changes anything? Wouldn’t you still get a bottleneck writing to the file?

In addition, I had a theoretical question about static methods: when a static method is synchronized, what object gets locked? Originally, I thought synchronization served to lock a method, but my book says two different objects can simultaneously execute a synchronized method–it’s only concurrent access to any one object that is controlled. In other words, it’s an object that gets locked–not a method–and a synchronized method checks to see if the object it is acting on has its lock set. So, if one synchronized method is acting on an object, it locks the object, and subsequently if another thread tries to call that method or any other synchronized method on the object, it has to wait until the object is unlocked. That lead to my theoretical question: how can you even declare a static method as synchronized when there is no object to lock? Static methods can be called when no objects of the class exist.

When you run a program, the JVM loads the classes that will be used during execution as an array of Class objects.

It is these objects that have the static methods associated with them, as well as the ‘class lock’ that would prevent multiple threads from accessing any synchronized static methods within a locked class.

As to your other question on block vs method sychronization, per 8.4.3.6 of the JLS, there is no difference (except synchronizing the methods requires less code…).

first of all you would put the synchronized block WITHIN the method, not visa-versa … in other words ONLY the lines of code that do the writing to the file would be within the block…

Im sure in theory it sounds ok … but I have to tell you I have seen some large synchronized methods turn an app into an absolute slug!

Personally I stay away from synchronized as much as humanly possible … its a bottleneck no matter how its handled so if theres a better way USE IT!

I think the last time I used it was dealing with a MySQL db (doesnt have the fun stuff the big dbs have) I needed to generate a key in one table and then use it to insert into 2 other tables so I added a block around the 1st insert, the code that retrieved the id and the 2 secondary inserts… besides that I cant remember the last time I used it. Again with real dbs you dont have these issues, you can simply use transactions.

And again 7 … although I understand the purpose of the lesson in the book I dont see too may real world uses for it… there’s not many times I would opt to write data to a flat file … thats what dbs are for

first of all you would put the synchronized block WITHIN the method, not visa-versa … in other words ONLY the lines of code that do the writing to the file would be within the block…

What possible difference could that make?

public sychronized void myMethod()
{
	System.out.println("user info");
}


public void myMethod()
{
	synchronized(this)
	{
		System.out.println("user info");
	}
}

public void myMethod()
{
     System.out.println("user info");
}
synchronized(this)
{
	myMethod();
}

As far as I can tell, you either create a bottleneck inside the method or outside the method–with no practical difference.

When you run a program, the JVM loads the classes that will be used during execution as an array of Class objects.

It is these objects that have the static methods associated with them, as well as the ‘class lock’ that would prevent multiple threads from accessing any synchronized static methods within a locked class.

As to your other question on block vs method sychronization, per 8.4.3.6 of the JLS, there is no difference (except synchronizing the methods requires less code…).

Thanks.