Groovy 线程安全 [英] Groovy Thread Safety

查看:158
本文介绍了Groovy 线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在多线程模式下使用 groovy 脚本执行.脚本本身是线程安全的.

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.

请帮忙.

推荐答案

如果没有实际的函数,我无法判断这是否应该是线程安全的.既然你说函数修改了上下文变量,我得出结论你改变了全局状态.在这种情况下,如果没有某种同步,它就不是线程安全的.如果我的假设是错误的并且没有全局状态发生变异,那么通过反射执行一个方法肯定不是问题

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

这篇关于Groovy 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆