Java Web Application Sync Question
Let's say I have a class in my web app called class "Foo". It has an initialise() method that is called when the bean is created using Spring. The initialise() method then tries to load an external service and assign it to a field. If the service could not be contacted, the field will be set to null.
private Service service;
public void initialise() {
// load external service
// set field to the loaded service if contacted
// set to field to null if service could not be contacted
}
When someone calls the method get() on the class "Foo" the service will be invoked if it was started in the initialise() method. If the field for the service is null, I want to try and load the external service.
public String get() {
if (service == null) {
// try and load the service again
}
// perform operation on the service is service is not null
}
Is it possible that I may have sync issues if I would do something like this?
Asked by: Daryl927 | Posted: 28-01-2022
Answer 1
toolkit's answer is correct. To solve the problem, just declare your Foo's initialise() method to be synchronized. You could refactor Foo as:
private Service service;
public synchronized void initialise() {
if (service == null) {
// load external service
// set field to the loaded service if contacted
}
}
public String get() {
if (service == null) {
initialise(); // try and load the service again
}
// perform operation on the service is service is not null
}
Answered by: Aida304 | Posted: 01-03-2022
Answer 2
Yes, you will have a sync problem.
Lets assume you have single servlet:
public class FooServlet extends HttpServlet {
private MyBean myBean;
public void init() {
myBean = (MyBean) WebApplicationContextUtils.
getRequiredWebApplicationContext(getServletContext()).getBean("myBean");
}
public void doGet(HttpRequest request, HttpResponse response) {
String string = myBean.get();
....
}
}
class MyBean {
public String get() {
if (service == null) {
// try and load the service again
}
// perform operation on the service is service is not null
}
}
And your bean definition looks like:
<bean id="myBean" class="com.foo.MyBean" init-method="initialise" />
The problem is that your servlet instance is used by multiple request threads. Hence, the code block guarded by service == null may be entered by multiple threads.
The best fix (avoiding double-checked-locking etc) is:
class MyBean {
public synchronized String get() {
if (service == null) {
// try and load the service again
}
// perform operation on the service is service is not null
}
}
Hope this makes sense. Drop a comment if not.
Answered by: John517 | Posted: 01-03-2022Similar questions
java - Synchronized, clustered JMS application (Weblogic)
First of all:
I am using Weblogic 11g with 3 managed servers and 3 JMS servers with a distributed queue and 3 saf agents (for sending the messages). The persistent store of all the JMS servers is stored in a network path - 3 files for 3 servers.
I need an application who sends a message to a queue (lets say output.jms.q) and then waits ...
java - how to achieve mutual exclusion using synchronized method in this application
i have run into a little problem in here. I am doing a concurrent program in Java. Problem is: There are 4 people (students) that are trying to access printer, to print 5 documents. But only one can print at the time (kind of obvious) 5 documents. When they finish they notify other that they done and other thread accesses the resource. i have a Main class, student class and Monitor (laser printer), Document class that hold...
java - Spring MVC application not synchronized
In my spring MVC application we have a below issue. We are new to spring and using spring 3.x. Will explain the problem below, please comment if not clear.
When we trigger concurrent requests at same time to below service and
Repository bean, the SampleBean object shown in below code is getting
overridden with the request that triggers later.
In other words the values of the SampleBean in T...
java - Thread Deadlock on synchronized Method in OSGi based application (Karaf)
We have an OSGi based application, which offers a central service interface to other bundles, one method of the service imlementation is synchronized:
MyServiceImpl implements Service {
@Override
public synchronized doSomething() {
}
}
Multiple threads access this service (e.g. a camel route and a webservice call) and call the doSomething() method at the same time. So, nothi...
java - Singleton class in Android application using synchronized initalizer
I need a single instance of one class to be used across my whole Android application.
I am using the following code to achieve this and I want to be sure that doing it like this is correct, thread-safe and doesn't have an impact on performance.
public class MyClass {
private static MyClass instance;
public static synchronized MyClass getInstance() {
MyClass myClass;
...
Java synchronized static methods: lock on object or class
The Java documentation says:
It is not possible for two invocations of synchronized methods on the
same object to interleave.
What does this mean for a static method? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?
c# - Does a cache need to synchronized?
This seems like perhaps a naive question, but I got into a discussion with a co-worker where I argued that there is no real need for a cache to be thread-safe/synchronized as I would assume that it does not matter who is putting in a value, as the value for a given key should be "constant" (in that it is coming from the same source ultimately). If the values can change readily, then the cache itself does not seem to be all...
concurrency - Java: A synchronized method in the superclass acquires the same lock as one in the subclass, right?
class A {
public synchronized void myOneMethod() {
// ...
}
}
class B extends A {
public synchronized void myOtherMethod() {
// ...
}
}
// ...
B myObject;
// ...
myObject.myOneMethod(); // acquires lock
myObject.myOtherMethod(); // same lock?
How I understand the synchronization model, I'd say that yes, it does, because the lock / monitor is associated with the...
java - In what situations could an empty synchronized block achieve correct threading semantics?
I was looking through a Findbugs report on my code base and one of the patterns that was triggered was for an empty synchronzied block (i.e. synchronized (var) {}). The documentation says:
Empty synchronized bloc...
java - proper usage of synchronized singleton?
So I am thinking about building a hobby project, one off kind of thing, just to brush up on my programming/design.
It's basically a multi threaded web spider, updating the same data structure object->int.
So it is definitely overkill to use a database for this, and the only thing I could think of is a thread-safe singleton used to contain my data structure.
java - Threads synchronized
I create two threads first thread to call application
and second thread for read file that result from calling application on the first thread.
Call application work fine but read the file doesn't work.
Here is my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package reciverwindow;
import java.util.logging.Level;
import java.util.logging.L...
java - Are Synchronized Methods Slower In Single Threaded Applications?
I've been debating this to myself for the last few minutes, and I'm seeing reasons for both yes and no. This stemmed from looking at the answers to Java HashMap vs. Hashtable and seeing several people say Hashtable is in fact slower.
It seems to me that a synchronized method should act absolutely no different than its unsync...
java - How to detect deadlock ? Timeout in synchronized block?
I’m debugging a Java application that runs several threads. After a while of watching the log it seems that one of those threads is not running anymore. My guess is that the thread is waiting for a lock that is never released (the last output is before calling a synchronized method).
Can I configure a timeout to the thread; a sort of “wait for this lock but if it not available after 10 seconds don’t wait any...
sql - Sharing a Java synchronized block across a cluster, or using a global lock?
I have some code that I want to only allow access to by one thread. I know how to accomplish this using either synchronized blocks or methods, but will this work in a clustered environment?
The target environment is WebSphere 6.0, with 2 nodes in the cluster.
I have a feeling that synchronized won't work, since each instance of the application on each node will have its own JVM, r...
performance - Where to look for synchronized contention evidence in java?
Our Tomcat web application feels slow when it is used by a couple hundred users. The servers are in a hosting company and their reports doesn't show any problem with bandwith or cpu workload, so I suspect that the reason of the slowdowns can be because of contention on some legacy code that we encapsulated under synchronized calls because it was the easier path.
I've done some artificial tests in the developement e...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)