• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

synchronization for static methods

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have created a helper class with many static methods. Some methods taking some input parameters and transforming it and returning the result. For eg. One method is taking a date in YYMMDD format and validating the date and returning a date in MM/DD/YYYY format.

These static methods are getting called by servlets or other java classes.

My question is:

1) Do I need to use synchronized keyword for these static methods?

2) Is there a thumbrule when to use static synchronized methods?

Any help is appreciated.

Thanks and regards,
Karan
 
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Synchronization is for concurrency issues. If you have multiple threads modifying a variable, then you have a concurrency issue and need to protect that variable.

If your static methods modify static variables, then you have a concurrency issue.

If the threads pass unique objects to the static methods and the static methods only modify those objects, then you don't have a concurrency issue.
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Karan it would have been better if you had directly asked your case but anyways here's how it goes

Multiple threads trying to access and compute some values and return the result.

So if all the threads are trying to modify a variable which is being shared by all threads race condition comes and usually turn into dead lock
thats why we use sync so that when a thread is modifying no other thread should interfere.
Now say threads are modifying their local variables now its doesn't matter what each thread is doing with its own version of that variable right? so sync is not needed
Also if its just read or write type operations (32 bit) e.g. reading an integer or writing it sync is not needed But if you are trying to read and write 1 step after the other then you need a sync


Basically Sync is used when you want a thread to execute a SEQUENCE of steps and don't want any other thread to interfere at that time

Man I don't know how much i cleared your doubt but PM me or continue writing into this thread
 
Abhijit Choudhury
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In your YYMMDD case I believe you dont need any Synchronization

because

threads are accepting parameter validating it computing new format
So all threads are computing their respective individual results and returning them.

Unless all threads are returning the result to the same place (which in your case will lead to overwriting if Sync is not used)

Also I forgot to mention Sync is used to avoid interference between threads but if each of their executions are independent Sync is not required. Here even though you may say I dont want these threads to interfere they time slice the CPU time and get the job done(independent jobs i.e.)
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mmmm, this method is probably using one or two SimpleDateFormats, correct? You may need synchronization of those SimpleDateFormat instances are held by static variables (which would be a common optimization to make). E.g.

Here convertDate() shoudl be synchronized, because every thread that calls convertDate() will access the same two mutable instances of SimpleDateFormat. Alternately, you could do this:

This requires no synchronization, because all the data is in local variables; it's never shared. However this may be wasteful because it creates two new SimpleDateFormats every time the method is called.

An efficient alternative is to use ThreadLocals:

Here each ThreadLocal saves a copy of the DateFormat that is unique to that thread. The first time a particular thread needs a DateFormat, it creates one (using the initialValue() method). Each subsequent time the same thread needs a DateFormat, it just reuses the same one it started with. So we do get multiple copies of identical DateFormats, but not nearly as many as we would have if new ones were created every time the method was called. So this can be a good way to achieve high performance in a highly concurrent environment. Of course it's also more complex-looking, so you may not want to bother with it in most other cases.
[ January 07, 2008: Message edited by: Jim Yingst ]
 
Abhijit Choudhury
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Deadlocks occur when multiple threads are trying to access a method which modifies something say for eg.

class A{
int m

void meth(){m=m+5;}
}

Now if multiple threads access the method may lead to inconsistent values
1 thread reads,2 thread reads, 1 thread computes, 2 thread may get more CPU time and computes and make changes ,1 thread changes or overwrites its value.You probably know this I have the habbit of beating around the bush again n again

But in your case threads are not modifying something that all the threads need to modify at the same time

There's no problem with multiple threads accessing same object all the threads will get their work done eventually

The question is, is the static method convertDate returning this final result string to a common place from where all threads again some how use it coz then you would need it to be synchronized or else you dont need your static function to be Synchronized

1 thread comes uses that indateFormat.parse() computes (local stuff) gives it to the outDateFormat.format() and it computes further(local stuff) and returns the value

Supposedly speaking some other thread comes during the execution of first thread (comes meaning gets CPU time).Also remember at a time only 1 thread runs dont be under the impression that all threads run simultaneously its just that these thredas context switch and time slice CPU time.

So 2 thread computes the final result and gives it out now the first thread again gets the CPU and finishes with the final result and gives it out, why doyou need a sync method let them time slice CPU time and compute the results making it sync doesnt allow other thread to use that method until 1 thread is done with it so it will take more time. The question is where does those final results go there's your answer.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi, fist of all i dont understand why you clubbed you question with poor example. If you want to know about synchronization the above give example are fair enough.

Comming ot you example mentioned in the question you entering some input and getting some output where there is no dynamic thing happening, i dont think synchronization will come into picture here
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[Abhijit Choudhury]: Deadlocks occur when multiple threads are trying to access a method which modifies something say for eg.

The term "deadlock" has nothing to do with anything in your example. It refers to something else entirely.

[Abhijit Choudhury]: So 2 thread computes the final result and gives it out now the first thread again gets the CPU and finishes with the final result and gives it out, why doyou need a sync method

In my last code, I gave three different examples. I don't know which of those three examples you are talking about here. The only example I gave that requires synchronization is the first one, where inDateFormat and outDateFormat are static variables, and thus the SimpleDateFormat instances are used by different threads. A SimpleDateFormat has mutable internal state, and the API for SimpleDateFormat tells us very clearly:

"Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."

In the first example in my last post, multiple threads can access the formats concurrently; therefore, they must be synchornized. In the second and third examples, multiple threads cannot access the formats concurrently, and no synchronization is needed.

[Yelamuri Chandu]: hi, fist of all i dont understand why you clubbed you question with poor example.

Who are you responding to here? And what does it mean to "club" a question?

I can't make sense of the rest of this response without some context. Which "you" are you responding to?
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
I think the problem is over compelxed here.
Karan ! for your question

Do I need to use synchronized keyword for these static methods?
To my mind answer is YES. if there are many classes that are accessing your utility methods at the same time then the chances are that they will bring discrepency in data. To avoid it you can synchronize your method.

Is there a thumbrule when to use static synchronized methods?
It totally depends on which context your methods are used. If its a multithreaded environment, you should go for synchronized methods.

regards...
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To my mind the answer is yes if there is shared data - e.g. if there are static fields being accessed by the methods. But if there isn't, then there is no need for synchronization.

Note that this question is 17 days old; it's unlikely the original poster is still paying attention anyway.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic