0

I am lost with a random error in my web application. I created a library to decode a code. I tried it a lot and never failed the test. But suddenly it starts to fail randomly. Since it works well in single-threaded tests and sometimes when it fails in a servlet environment, the only explanation I can imagine is that the problem is related to a library that is used in a multi-threaded environment. To be honest, I know that multithreading is a very complex issue. My fear is that my library may not be thread safe. It is very simple, by the way, it is a frontal class with several static methods. Basically, suppose you are using an array with some characters linked to other characters. The algorithm only looks inside the array and translates the input characters to the desired output characters. Can such an algorithm fail when used in a multi-threaded environment? I know there are few people able to help with an issue like this, but asking here is the only option in the middle that I am trying to better understand how a Java server like Tomcat treats common resources.

lm2a
  • 835
  • 1
  • 10
  • 19
  • Yes it can be fail very easily since you are iterating and updating the values in the array, If you can put a sample code it will help you to get a quick solution. – Amit Kumar Lal Oct 11 '19 at 10:28
  • Is your library completely stateless (can you change any internal state in it)? – Nyamiou The Galeanthrope Oct 11 '19 at 10:34
  • Thanks for your answers, when at home I will uploading code. But when a method is declared static does not mean there will be a copy for each instance. Because it is not an object. Am I wrong. – lm2a Oct 11 '19 at 11:12
  • You said, "static methods." Discussions about thread-safety should never focus on the methods: They should focus on the _data_. If your library methods (static or otherwise) potentially could be called from more than one thread, and if it would make sense for those calls to access the same data (which probably is guaranteed if the data are `static`.) Then that's where you'll want to focus your attention. – Solomon Slow Oct 11 '19 at 15:30

1 Answers1

0

When you have a member variable getting manipulated(reassigned or mutated) by a method which is accessed by multiple threads make that method synchronized.

user12047085
  • 162
  • 1
  • 12
  • watch out, the issue is about static methods – Curiosa Globunznik Oct 11 '19 at 11:16
  • Perhaps I am wrong and the problem is not on the library. I just had testing the library executing three threads simultaneously, each one is looping 1000 times using that static method and it never failed. – lm2a Oct 11 '19 at 18:01