Search code examples
javamultithreadingstatichttpserverexecutor

Does invoking two concurrent mains of the same class influence its own static variables?


i'm building a HTTP Server (link) and i'm using

 Executors.newCachedThreadPool() 

to awswer my requests. The handler that resolves such requests runs the following code:

  IntFactorization.main(input);

where IntFactorization is an instrumented class in such way that I have to mandatorily use the main method. The instrumentation class has all of this methods and attributes as static. Its methods are also synchronized.

The main of IntFactorization is like this:

public static void main(String[] args) {

IntFactorization obj = new IntFactorization();

int i = 0;



System.out.println("Factoring " + args[0] + "...");

ArrayList<BigInteger> factors = 

  obj.calcPrimeFactors(new BigInteger(args[0]));

System.out.println("");

System.out.print("The prime factors of " + args[0] + " are ");



for (BigInteger bi: factors) {

  i++;

  System.out.print(bi.toString());

  if (i == factors.size()) {

    System.out.println(".");

  } else {

    System.out.print(", ");

  }

}





System.out.println("");

}

My server has to awswer multiple requests concurrently and as we set server executor to

 Executors.newCachedThreadPool();

However, analysing the results I noticed that for the same number, the result of its factorization is not always the same. I think it might be (but I would like for you to confirm) that the fact of the code being instrumentated with static variables mean that if a server runs two executors then the threads are influencing one another?


Solution

  • I don't understand the bit about an "instrumentation class", but the title of your question is interesting.

    Does invoking two concurrent mains of the same class influence its own static variables?

    There's nothing special about a public static void main(String[] args) method in the Java language.

    A standard JVM will call the method with that name and argument signature if you give the name of its class on the JVM command line, but that's the JVM. That's not Java.

    Apart from main(...) being useable as an entry point for an application, it is otherwise just like any other static method. It will "influence" the static variables of its class (or, of any other class) if that's what it was written to do. If two or more threads make overlapped calls to main() at the same time, that's just like two or more threads making overlapped calls to any method at the same time.