Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

multithreading - Groovy Thread Safety

I am using groovy scripting execution in multi threaded mode. Script themselves are thread safe.

Its like below: //Startup Code. Single threaded

Class<?> scriptClass = getScriptClass(fileName); //utility to get script class from file name
Method method = getMethods(scriptClass); //Utility to get a specific Method
storeMethod(method); //Store method globally.
Object scriptInstance = scriptClass.newInstance();
storeScriptInstance(scriptInstance); //Store script Instance

Multiple threads execute following code: (without any synchronization.)

ScriptInstance scriptInstance = getScriptInstance(); //Utility to get scriptInstance stored in init
Method method = getMethod(); //Utility for getting method stored in init step
Object obj[] = new Object[] { context }; //context variable available per thread.
method.invoke(scriptInstance,obj);

script consists of just one function which is totally thread safe (function is reentrant and modifies context variable.)

This works in my unit testing with multiple threads but couldn't find any material to support this claim. Question => Is it safe under multiple thread execution? More generically, sharing of same script instances across threads to execute scripts functions which themselves are thread safe is safe? Script instances shouldn't have global variables in execution. Context is an argument to script and not global variable.

Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without the actual function I cannot tell if this is supposed to be threadsafe or not. Since you say that the function modifies the context variable I conclude that you mutate global state. In that case it is not threadsafe without synchronization of some kind. If my assumption is wrong and no global state is mutated, then executing a method by reflection is surely not the problem


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...