How to Run 'Before' Case only once for multiple threads - junit

I have a Junit Test Sampler that has to run with 100 threads, but i want the before case for the same to run only once. How can i do this scenario?

Something like:
#Override
public void setUp(){
JMeterContext ctx = JMeterContextService.getContext();
JMeterVariables vars = ctx.getVariables();
if (ctx.getThreadNum() == 0 && vars.getIteration()==1) {
//your code here
}
}
Will trigger your setup code only for 1st thread and 1st iteration.
References:
JMeterContext
JMeterVariables
How to Use JUnit With JMeter

Add your samplers under Once Only controller. They will be executed only once for each thread and should solve your problem.
You can refer to http://jmeter.apache.org/usermanual/component_reference.html#Once_Only_Controller

Related

what does particleEmitter.start() method do in particle emitter class?

whether I put start() method or not my particle emitter runs the same way, So what is the use of start() method.
If you look at the source code of ParticleEffect class and then look at the start method, you will see this -
public void start () {
for (int i = 0, n = emitters.size; i < n; i++)
emitters.get(i).start();
}
Basically, this means it is going through all the emitters and calling ParticleEmitter#start method.
Now let's look into the start method of ParticleEmitter.
public void start () {
firstUpdate = true;
allowCompletion = false;
restart();
}
Basically from the method, you can see that its setting the firstUpdate boolean to true which means "this is the first update" i.e. we will be doing something for the first time (look into the source code to see where the boolean is used)
The next line, it is setting allowCompletion to false which means, if the emitter was already in progress, don't let it complete (Check source code to see where the boolean is used)
The final call is to restart() which is self-explanatory (restarting this emitter if it was already running.)
I hope that helped.

Does every WinRT/Windows Core thread have a Dispatcher?

We're providing a library that needs to run code on its own custom threads. Once done, I want these threads to call callbacks (event handlers) through a Dispatcher (System.Windows.Threading.Dispatcher). The library user shall use the Dispatcher to dispatch event handling to.
We could simply always dispatch on CoreApplication.MainView.CoreWindow.Dispatcher but not all programs (e.g. Windows 10 IoT Core apps) provide an UI and thus they lack a main window.
Can the user simply refer to System.Windows.Threading.Dispatcher.CurrentDispatcher to get his thread's Dispatcher? Or can't all threads have a Dispatcher?
Edit: Here's more context for this question. Hopefully it makes the question easier to grasp: https://github.com/getsenic/nuimo-windows/issues/2
For first, I'm not sure, that you should execute event handlers on UI thread, because only client knows if he needed access UI elements.
For second, before invoking CoreApplication.MainView property you can check CoreApplication.Views.Count > 0 (I'm not absolutely sure that it will work because currently I don't have device to test it).
And also you can solve this issue in another way: in constructor of you object save the SynchronizationContext of executing thread and then use it to raise events. It will work if your object instantiates from UI thread (in most cases it's true). That way you can completely refuse from Dispatcher.
public class NotifierExample
{
private readonly SynchronizationContext _synchronizationContext;
public event EventHandler SomethingHappened;
public NotifierExample()
{
_synchronizationContext = SynchronizationContext.Current;
}
public void Do()
{
Task.Factory.StartNew(() =>
{
//do something
OnSomethingHappened();
});
}
private void OnSomethingHappened()
{
if (_synchronizationContext != null)
{
_synchronizationContext.Post(o => RaiseSomethingHappened(), null);
}
else
{
RaiseSomethingHappened();
}
}
private void RaiseSomethingHappened()
{
var somethingHappened = SomethingHappened;
somethingHappened?.Invoke(this, EventArgs.Empty);
}
}
Or can't all threads have a Dispatcher?
Dispatcher threads are always tied to UI threads. IoT headless mode app does not have an UI so it does not have a Dispatcher thread.
Can the user simply refer to System.Windows.Threading.Dispatcher.CurrentDispatcher to get his thread's Dispatcher
System.Windows.Threading.Dispatcher.CurrentDispatcher is only supported in legacy .NET platform. The UWP alternative is CoreApplication.MainView.CoreWindow.Dispatcher as you pointed out.
If you want to to do async callbacks in Headless(without GUI) mode, you can probably refer to Task Parallel Library(TPL), the ContinueWhenAll ContinueWhenAny etc API... might well suits your needs. Refer to https://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.aspx.

Deferring PropertyChanged events until view bindings setup complete

A number of our MVVMcross views depend remote services to fully display themselves. We typically kick this off a Task in ViewModel's Init() using to get it async. ViewModel properties are set in the Task upon completion, UI updated via PropertyChanged notifications.
Sometimes the remote data (and task) completes before the View has bound it's listeners and thus no property changed event is received.
This issue is touched on at async Init and Property Changed in MvvmCross but the solution feels like duplication of presentation logic.
We've had success buffering PropertyChanged notifications until the end of ViewDidLoad, but we'd like to turn below into a more generic solution by hooking into the MVX framework.
Is there a way to hook mvvmcross's view creation to fire our code off after viewDidLoad completes?
Base View Model
public abstract class BaseViewModel : MvxViewModel{
protected bool _deferPropertyChangedEvents = true;
private readonly List<PropertyChangedEventArgs> _deferedPropertyChangedEvents = new List<PropertyChangedEventArgs>();
public override void RaisePropertyChanged(PropertyChangedEventArgs changedArgs)
{
lock(_deferedPropertyChangedEvents){
if (!_deferPropertyChangedEvents)
{
base.RaisePropertyChanged(changedArgs);
}
else
{
// buffer it up
_deferedPropertyChangedEvents.Add(changedArgs);
}
}
}
public void EndDeferringPropertyChangedEvents()
{
lock(_deferedPropertyChangedEvents){
_deferPropertyChangedEvents = false;
// playback all buffered notifications
foreach (var e in _deferedPropertyChangedEvents)
{
RaisePropertyChanged(e);
}
_deferedPropertyChangedEvents.Clear();
}
}
}
Sample view
public class SomeView : MvxViewController
{
public override void ViewDidLoad()
{
base.ViewDidLoad();
var bindings = this.CreateBindingSet<StopView, SomeViewModel>();
.....
bindings.Apply();
// plays back any PropertyChanged() notifications that were buffered
// up while the view was initializing
// ---> want to find a way to have MVX call this
ViewModel.EndDeferringPropertyChangedEvents();
}
}
As a simple answer, I believe your own line can easily be called using a BaseViewModel cast:
// ---> want to find a way to have MVX call this
((BaseViewModel)ViewModel).EndDeferringPropertyChangedEvents();
However, on a more technical note, I think it might be useful to further examine and understand why this Deferring code is necessary - to further take a look at what the underlying threading problems are.
There are a number of factors that are puzzling me at present::
During the line bindings.Apply(); all current bound property values should be transferred from the ViewModel to the View - so calling EndDeferringPropertyChangedEvents(); in the next line should (in theory) only rarely get different values.
Further, the default MvvmCross RaisePropertyChanged method changed notifications across to the UI thread. Because ViewDidLoad is also invoked on the UI thread, this means that any RaisePropertyChanged calls made on background threads during ViewDidLoad should all be automatically deferred until after ViewDidLoad has finished and the UI thread becomes available.
Looking at the MvxNotifyPropertyChanged code, the only potential gap I can see where mutli-threading might find a way through this automatic RaisePropertyChanged deferral is in this optimisation check:
// check for subscription before potentially causing a cross-threaded call
if (PropertyChanged == null)
return;
(from https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross/ViewModels/MvxNotifyPropertyChanged.cs#L76)
If your ViewModel Init method is also using async for it's Task management, then this async code should also be using the UI thread - so the "callback" of this async operation should also be marshalled back to the UI thread (and so shouldn't be executed during ViewDidLoad itself).
As I said, these factors are puzzling me - I don't have a definitive answer/explanation - sorry! But I'd love to see an example problem and to try to help solve it at a generic level.

JRuby - stopping script execution

Is there any way to stop a script after it has executed a particular amount of time?
This is a rather vaguely defined question. Here are a few ideas that come to mind:
Use a shell as the control process. Start the JRuby script, send it into the background, sleep for a fixed amount of time, then kill $!.
At the beginning of your JRuby script, create a thread that sleeps for a fixed amount of time, and then kill the entire script.
If you're using an embedded JRuby, you can use Java's threads to do exactly what you want.
I have the same question. My current approach looks like this (and does not work as expected...):
// jruby-complete-1.6.0.RC2.jar
import org.jruby.Ruby;
class JRubyStop {
public static void main(String[] args) throws InterruptedException {
final Ruby jruby = Ruby.newInstance();
Thread jrubyThread = new Thread() {
public void run() {
String scriptlet = "for i in 0..100; puts i; sleep(1); end";
jruby.evalScriptlet(scriptlet);
}
};
jrubyThread.start();
Thread.sleep(5000);
System.out.println("interrupt!");
jrubyThread.interrupt();
System.out.println("interrupted?!");
}
}
After the output of "interrupted?!" the thread still runs until the scriptlet ends.
Edit: Converted Groovy example into a Java SSCCE (http://sscce.org/).
super late answer but this is what I use:
require 'timeout'
status = Timeout::timeout(5)
{
# Something that should be interrupted if it takes more than 5 seconds...
}

SSIS Script Component with Multiple Inputs

I am looking for a way to create a script component within SSIS which will accept multiple inputs.
I need this so I can do a form of custom joining.
It seems really silly that a script can have multiple outputs but only one input, I'm sure I must be doing something wrong.
Any help?
try putting a Union All component before your script component, and rather than having the columns match up, add columns to the output so that each element coming in winds up in a unique column.
Keep in mind that at first the SSIS script component will process items row by row, so a custom joining mechanism will need to be done using some collections and capturing the event that fires after all the rows have been processed.
Please keep in mind that I'm assuming you're using a script component in the Data Flow and not the Control Flow, and that I'm assuming you're using SSIS 2005.
I'm currently experimenting with using SSIS variables to pass synchronization objects from one script component to another. It's rather clumsy, but you can effectively use multiple script components to accept various inputs, and then use the System.Threading classes to sync passing values from one script component to another.
The hurdle is that each script is in its own namespace and can't share classes with other scripts (unless you want to compile & deploy your own assembly with SSIS). What I'm currently doing is passing (over the shared variable) a reference to an object[], containing a reference to a ManualResetEvent, the SSIS PipelineBuffer, and an array of pipeline column indices.
This is enough to allow the receiving script to reconstruct the other script's input pipeline, pump it dry, then signal back that it's finished.
It's functional, though I'm currently looking for work-arounds to the fact that (it would seem) SSIS invokes "ProcessInput" twice during a script component's life time. If any of the geniuses here on SO have a solution to that, then I think we've pretty much got a [clumsey] solution to allowing multiple inputs to a single script component.
Any takers?
---- EDIT----
I've got this up and running - this trick is to use syncronization to prevent the multi-threaded invocation of ProcessInput from attempting to share th input buffer mulitple times. Below is a crude code sample of how I got this working:
Script Component 1: Shares its input...
using System;
using System.Collections;
using System.Threading;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Microsoft.SqlServer.Dts.Pipeline;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
System.Collections.Generic.List<object> shared = null;
System.Threading.ManualResetEvent sync;
public override void ProcessInput(int InputID, PipelineBuffer Buffer)
{
lock (this)
{
if (InputID == 82)
{
if (shared == null)
{
shared = new System.Collections.Generic.List<object>();
sync = new System.Threading.ManualResetEvent(false);
shared.Add(sync);
shared.Add(Buffer);
shared.Add(GetColumnIndexes(InputID));
IDTSVariables100 vars = null;
this.VariableDispenser.LockOneForWrite("Test", ref vars);
vars[0].Value = shared;
vars.Unlock();
sync.WaitOne();
System.Windows.Forms.MessageBox.Show("Done");
}
}
}
}
}
... then Script Component 2 (which consumes Script Component 1's input)...
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
System.Threading.ManualResetEvent sync = null;
InputXBuffer sharedBuffer = null;
public override void Input0_ProcessInput(Input0Buffer Buffer)
{
lock (this) // Only 1 thread at a time
{
if (sharedBuffer == null)
{
object Test = null;
while (Test == null)
{
System.Threading.Thread.Sleep(100);
IDTSVariables100 vars = null;
this.VariableDispenser.LockOneForRead("Test", ref vars);
Test = vars[0].Value;
vars.Unlock();
}
var sharedList = Test as System.Collections.Generic.List<object>;
if (sharedList != null)
{
sync = sharedList[0] as System.Threading.ManualResetEvent;
var buffer = sharedList[1] as PipelineBuffer;
var bufferColumnIndexes = sharedList[2] as int[];
sharedBuffer = new InputXBuffer(buffer, bufferColumnIndexes);
}
}
}
while (sharedBuffer.NextRow())
{
// ... do stuff with Script Component 1's shared input here...
}
sync.Set(); // Signal script 1 that we're done
}
}
The scripts both share a read/write variable called "Test" - you can change the variable name to suite your needs. Hopefully the above serves as a working model for you to take this to the next level.
PS:- If you have the time & energy, writing a proper custom SSIS component really is the way to go for multi input scenarios.