• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

local variable in static method be changed?

 
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hopefully I'm explaining this probably dumb question correctly:
Consider the following method:

Without synchronizing this method can the variable of localString be modified before the print statement if another object calls someMethod() and when it hits the processing it takes a shorter amount of time than the first object's processing?
I normally create a bunch of static utility methods that any class can use, but if the above is true I'm starting to think this is a bad idea. Like just for example I have a method:

Now I'm starting to wonder if it's a bad to make these methods static? In theory couldn't another object call this method and change the return value from what the original object calling the method would expect? (Obviously in this case processing would probably be so fast it would never happen).
Making utility methods synchronized would seem to really hinder performance yet I like him having them static since I really don't an instance of the whole Utility class in order to access a utility/helper method in that class.
I'm also studying for the exam so I thought I'd ask it here, even though it may be more of an architecture type question.
Any help much appreciated.
Thanks,
Rick
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to synchronize the static parts of a class if you want it threadsafe. Don't forget that you can synchronize parts of your code on any arbitrary object (the object monitor of the class will be used for synchronization) with the synchronize (objectname) { .... } construct. That'll make your synchronization strategy more fine-grained.
Cheers,
Magnus
[This message has been edited by Magnus Lidman (edited November 27, 2001).]
[This message has been edited by Magnus Lidman (edited November 27, 2001).]
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rick,
I wouldn't really worry about it because that is the way the Math package was created. As long as you keep the methods short you should have no problems. Also, make sure you have a good reason to create a local copy of a variable. Since Java passes arguments by Value you can't change the original value anyway. For example:
public class Tester
{
public static void main( String[] args )
{
int i = 23;
System.out.println( addOne( i ) ); // Prints "23"!
}
public static void addOne( int j )
{
++j;
}
}
Regards,
Manfred.
 
Rick Reumann
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Manfred Leonhardt:
Hi Rick,
I wouldn't really worry about it because that is the way the Math package was created. As long as you keep the methods short you should have no problems. Also, make sure you have a good reason to create a local copy of a variable. Since Java passes arguments by Value you can't change the original value anyway.
...
Regards,
Manfred.


Yes, I only added the local copy for illustration.
I'm starting to think though that some of my classes would be best as instance classes. Like for example I have a static method that takes a request object and from that object then goes ahead and populates a bean with all those request parameters. Now being that this method is static and shared across all who use the web application users could end up altering the bean's creation. In this case the question I think becomes is it better to synchronize a static method or make it an instance method. It seems best in this case to make an instance method since then all the users are waiting around to have access to a static method.
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


In theory couldn't another object call this method and change the return value from what the original object calling the method would expect?


Because String objects are inmutable that's not possible. However if it were a mutable object that is shared between several threads I think it would be advisable to synchronized the methods that can access the shared data.


I'm starting to think though that some of my classes would be best as instance classes. Like for example I have a static method that takes a request object and from that object then goes ahead and populates a bean with all those request parameters. Now being that this method is static and shared across all who use the web application users could end up altering the bean's creation. In this case the question I think becomes is it better to synchronize a static method or make it an instance method. It seems best in this case to make an instance method since then all the users are waiting around to have access to a static method.


IMHO this is a case for making local copies of the request parameters that could be shared between different invocations of the method. The intention must be provide each invocation with a set of unique values if those values could be modified by other invocations to the method. The objects that compound the parameter could be modified if they are shared between different threads and they are mutable. Otherwise, given that each method invocation creates its own space to save its parameters or local variables, there is no problem.
By the way are you sure that the invocation of the method ocurred in a multithreaded enviroment?. Maybe they are only enqueued.
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Tester
{
public static void main( String[] args )
{
int i = 23;
System.out.println( addOne( i ) ); // Prints "23"!
}
public static void addOne( int j )
{
++j;
}
}
"void type not allowed here
System.out.println( addOne( i ) );"
 
Rick Reumann
Ranch Hand
Posts: 281
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your help Jose. If I could indulge you further consider the following simple code bit:


Now I believe if this static method was residing in a class as part of a web application, all users would be sharing this same static method (I assume this would be considered a multithreaded environment but I'm not certain). I guess what I'm confused about is what happens in the above situation when an object calls the method and then a split second later another thread (in this case say another user of the web application) calls the same method? Isn't it possible the second method call could go ahead and change what the variables 'name' and 'age' are referencing and thus return a totally different unexpected Person object?

The intention must be provide each invocation with a set of unique values if those values could be modified by other invocations to the method.


Sorry, I'm not totally sure I'm following you with the above. Could you provide a simple example?


The objects that compound the parameter could be modified if they are shared between different threads and they are mutable. Otherwise, given that each method invocation creates its own space to save its parameters or local variables, there is no problem. By the way are you sure that the invocation of the method ocurred in a multithreaded enviroment?. Maybe they are only enqueued.



I guess I need to do some more research It's pretty sad I've been doing JSP for a while now and it wasn't until I started studying for this exam that I began to think about some of these things on a deeper level I'm pretty sure a JSP application residing on an app server is running in a mutlithreaded environment since I know each user is accessing stuff independently of the others. I need to explore more what happens when they are both accessing a static method at near the same time. I don't think I've run into any problems so far simply because the applications are getting hit on a grand scale and don't involve a lot of processing time. Still I want to do the "right" things.
I would appreciate more of your insights. Feel free to email me off the forum at reumann@hotmail.com if you believe this topic has gone out of the certification realm of discussion.
Thanks so much,
Rick

[This message has been edited by Rick Reumann (edited November 27, 2001).]
[This message has been edited by Rick Reumann (edited November 27, 2001).]
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public static Person createPersonFromRequest( HttpServletRequest req ) {
Person p = new Person();
String name = req.getParameter("name");
int age = Integer.parseInt( req.getParameter("age");
//1.
p.setName( name );
p.setAge( age );
return p;
}
If this method could be called concurrently by two threads there is only one issue to be concerned. The paremeter to the method is unique for each invocation?
I guess it is because a HttpServletRequest must represent a user request that is unique to a user. Once the age and name of the request are obtained they can not be changed by other invocation because both are inmutable and they are stored in the local variable section of the mehtod frame. Each invocation of a method spawns such (private to the method) zone. Thus the local variables are safe there.
One danger could be if a local variable points to the same object as the same local variable does in another invocation of the same method that is concurrently executing. In this case one method could modify the object, that is shared between the two methods invocations, in a way that is not expected by the other method invocation. In this case sychronizins the part of the methods that access the shared data will avoid the danger.
For instance:
void method(Object o) {
o.intField++;
System.out.println(o.intField);
}
this example is not particularly useful, but imagine that the method modifies the argument state (increment) and does some operation (println).
If the method were invoked by two threads passing it the same object, because the method is not synchronized we could have the following scenario:
one thread increments the field. The other increments it again, now both prints will show a value that was incremented by two, instead of by one as the intention of the method was. To solve this problem just utilize synchronized or clone the parameter within the method. The last is not a standar solution but sometimes it could be considered.
Now in your example I don't think different invocations will get the same paremeter, so I don't see any problem here. Besides that you don't modify them, you only read them.
 
Weeds: because mother nature refuses to be your personal bitch. But this tiny ad is willing:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic