英文:
Mixing data in abstract class when working in parallel
问题
我在我的抽象类中遇到了问题,我有一个约有 2000 名用户的应用程序,并且许多用户同时对不同的类进行调用,这些类共享一个抽象类。
class A extends B {
// 代码
}
当在我的抽象类中接收到一些方法的参数时,在这种情况下,所有类都调用这些方法会产生不便。
abstract class B {
public int getResult(int b){
return b+1;
}
}
class C extends B {
public int getValue(int a){
int b = getResult(a);
int c = b * 2 / 4;
return c + 150;
}
}
当多个人并行进入类 'C' 并向方法 getResult 传递不同的参数时,最终会混淆发送的数据,并返回错误数据。
我找到的解决方法是在每个类中实现 getResult 方法,但这会导致我在每个类中重复编写代码,而大约有 200 个类实现了该抽象类。
我已经阅读到使用封装可以避免这种情况,但我不知道是否是选项,因为我还没有在这方面进行过工作。
我已经尝试使用 synchronized,但这造成了许多瓶颈,并且响应时间增加了。
英文:
I have a problem with my abstract class, I have an app for about 2000 users and many make calls at the same time to different classes, those classes share an abstract class
class A extends B{
//Code
}
The inconvenience arises when in my abstract class I receive parameters to some of my methods that in this case all classes call these methods.
class abstract B {
public int getResult(int b){
return b+1;
}
}
class C extends B {
public int getValue(int a){
int b = getResult(a);
int c = b * 2 / 4;
return c + 150;
}
}
When several people in parallel enter the class 'C' and pass different parameters to the method getResult ends up mixing the data sent and returns erroneous data in the execution.
The option that I have found is to implement the getResult method in each class, but that makes me repeat code in each class and there are about 200 classes that implement that abstract class
I've read that with encapsulation I can avoid that, but I don't know if that's the option since I haven't worked on it.
I have used the synchronized but it has created many bottlenecks and response times have increased.
答案1
得分: 1
我认为你需要在你的getValue方法中使用synchronized来管理对该方法的并行访问。也许这篇文章可以帮助你,它还有一个简单的示例:https://dzone.com/articles/java-concurrency-synchronization#:~:text=the%20credit%20method
- 注意B类的前面必须有"abstract"关键字。
- 在你的getValue方法中添加"synchronized"关键字。
就像这样:
abstract class B {
public int getResult(int b){
return b+1;
}
}
class C extends B {
public synchronized int getValue(int a){
int b = getResult(a);
int c = b * 2 / 4;
return c + 150;
}
}
英文:
I think you need use synchronized in your getValue method to manage parallel access to yout method. Maybe this article can help you, have a simple example too: https://dzone.com/articles/java-concurrency-synchronization#:~:text=the%20credit%20method
- Note B class must have _"abstract" keyword before class.
- Add "synchronized" in your getValue method
This way:
abstract class B {
public int getResult(int b){
return b+1;
}
}
class C extends B {
public synchronized int getValue(int a){
int b = getResult(a);
int c = b * 2 / 4;
return c + 150;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论