Java: ThreadLocal get() method alternative - java-8

I was wondering, is there an elegant way to get the Threadlocal initialValue?
The reason I'm asking this is because I'm converting a non thread safe project into a thread safe one, problem is, there are nearly a thousand different class fields that cannot be shared between all threads and must be exclusive to each thread, thus using ThreadLocal solves that.
Problem is once fields are converted to ThreadLocal, on every field usage in the code , I must add a .get() to it which will probably take me light years to accomplish.
For example:
Declare the field:
private ThreadLocal<String> field1 = new ThreadLocal<>();
initialize the field:
field1.set("input");
print the field:
System.out.println("field1 = "+field1.get());
there must be an IDE shortcut that probably solves that.
But thinking about code appearance, code meaning, elegance and future development, My Goal with this post is to know if there's an elegant way of achieving the ThreadLocal's field value just like in C# where you have a field property that you can wrap it the way you desire, and by simply typing down the field's name you're getting it's value
What I wish to achieve:
Declare the field:
private ThreadLocal<String> field1 = new ThreadLocal<>();
initialize the field:
field1.set("input");
An elegant wrapper:
{some ThreadLocal.get() property wrapper}
print the field:
System.out.println("field1 = "+field1);
Overall, I'm for somewhat reason not satisfied at all with the .get() solution..
Any suggestions?

Related

Should I use Map<string, Map<string, object>> or Map<string, object> and concat the two keys

I'm working on processing some data and I need to keep a previous state. That state data structure would be something like
type locationId = string;
type alarm = {
alarmId : string,
triggered: Date,
urgency: string
}
type stateData = Map<locationId, Map<alarmId, alarm>> OR Map<locationId+alarmId, alarm>;
In pseudocode it would look like:
for each alarm in alarmList
compare(lastState[locationId][alarm.alarmId], alarm)
or if I concat the two keys:
for each alarm in alarmList
compare(lastState[locationId + "-" + alarmId], alarm)
Which one is the best approach?
How you do this will depend on your data and how you want to access it, and perhaps most importantly how you want to think about it.
Consider the dictionary with a combined key. Something like
type alarmKey = {
locationId: string;
alarmId: string;
}
type alarms = Map<alarmKey, stateData>
With that design, you have to know the location and the alarm ID if you want to look up an alarm. There's no quick way, for example, to get all of the alarms for a particular location. Instead, you have to scan the entire dictionary looking for alarms where alarmKey.locationId="Desired location".
That might not be a bad thing. If your total number of alarms is small (i.e. the map isn't huge) or if getting the list of alarms for a single location isn't a common operation, then that's not a bad thing.
Do note, by the way, that if you go that route you'll need to define a hash code method that will create a hash code for the combined key. You don't say what language you're using. In C#, that method could be as simple as:
return (locationId+alarmId).GetHashCode();
(Yes, I know that it's a horribly inefficient way to compute a hash code for a combined key. But it will in fact work. I'll leave coming up with a better one as a detail to be resolved by the implementor.)
The other way, with a nested map, seems more flexible to me. That is:
type alarms = Map<locationId, Map<alarmId, stateData>>
That lets you easily get all alarms for a single location, and it's also easy to look up an individual alarm.
You're probably going to supply an accessor anyway, so either way will be just as easy to use. That is, regardless of which way you design it, you'll probably have a getter function:
alarm GetAlarm(locationId, alarmId)
{
}
And of course a corresponding setter function.
I don't have knowledge of your application, but when I've encountered this kind of thing in the past my immediate preference is for the nested maps because I find it more flexible. But I readily admit that it's largely a subjective thing, and dependent on the application.

Best way to validate and extend constructor parameters in Scala 2.10

I want to have a class that has a number of fields such as String, Boolean, etc and when the class is constructed I want to have a fieldname associated with each field and verify the field (using regex for strings). Ideally I would just like specify in the constructor that the parameter needs to meet certain criteria.
Some sample code of how :
case class Data(val name: String ..., val fileName: String ...) {
name.verify
// Access fieldName associated with the name parameter.
println(name.fieldName) // "Name"
println(fileName.fieldName) // "File Name"
}
val x = Data("testName", "testFile")
// Treat name as if it was just a string field in Data
x.name // Is of type string, does not expose fieldName, etc
Is there an elegant way to achieve this?
EDIT:
I don't think I have been able to get across clearly what I am after.
I have a class with a number of string parameters. Each of those parameters needs to validated in a specific way and I also want to have a string fieldName associated with each parameter. However, I want to still be able to treat the parameter as if it was just a normal string (see the example).
I could code the logic into Data and as an apply method of the Data companion object for each parameter, but I was hoping to have something more generic.
Putting logic (such as parameter validation) in constructors is dubious. Throwing exceptions from constructors is doubly so.
Usually this kind of creational pattern is best served with one or more factory methods or a builder of some sort.
For a basic factory, just define a companion with the factory methods you want. If you want the same short-hand construction notation (new-free) you can overload the predefined apply (though you may not replace the one whose signature matches the case class constructor exactly).
If you want to spare your client code the messiness of dealing with exceptions when validation fails, you can return Option[Data] or Either[ErrorIndication, Data] instead. Or you can go with ScalaZ's Validation, which I'm going to arbitrarily declare to be beyond the scope of this answer ('cause I'm not sufficiently familiar with it...)
However, you cannot have instances that differ in what properties they present. Not even subclasses can subtract from the public API. If you need to be able to do that, you'll need a more elaborate construct such as a trait for the common parts and separate case classes for the variants and / or extensions.

How can I modify the fixture my custom theory data attribute creates for AutoFixture?

I'm really appreciating the power of AutoFixture coupled with XUnit's theories. I've recently adopted the use of encapsulating customizations and providing them to my tests via an attribute.
On certain occasions, I need a one-off scenario to run my test with. When I use an AutoDomainDataAttribute, like above, can I ask for an IFixture and expect to get the same instance created by the attribute?
In my scenario, I'm using MultipleCustomization by default for collections, etc. However, in this one case, I want only a single item sent to my SUT's constructor. So, I've defined my test method like so:
[Theory, AutoDomainData]
public void SomeTest(IFixture fixture) {
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
...
}
Unfortunately, I'm getting an exception when creating the anonymous Product. Other tests work just fine, if I ask for a Product as a method parameter with those attributes. It's only an issue in this particular case, where I'm hoping that the fixture parameter is the same one created by my AutoDomainDataAttribute.
Product's constructor expects an IEnumerable that normally gets populate with 3 items, due to the customizations I have in-place via AutoDomainData. Currently, my DomainCustomization is a CompositeCustomization made up of MultipleCustomization and AutMoqCustomization, in that order.
The exception is: "InvalidCastException: Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'Product'."
If you need the same Fixture instance as the one active in the attribute, you can inject the Fixture into itself in a Customization, like this:
public class InjectFixtureIntoItself : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Inject(fixture);
}
}
Just remember to add this to your CompositeCustomization before AutoMoqCustomization, since IFixture is an interface, and if AutoMoqCustomization comes first, you'll get a Mock instance instead - AFAICT, that's what's currently happening with the dynamic Castle proxy.
However, if you really need a Fixture instance, why not just write a regular, imperative test method:
[Fact]
public void SomeTest()
{
var fixture = new Fixture().Customize(new DomainCustomization());
fixture.RepeatCount = 1;
var sut = fixture.CreateAnonymous<Product>();
// ...
}
That seems to me to be much easier... I occasionally do this myself too...
Still, I wonder if you couldn't phrase your API or test case in a different way to make the whole issue go away. I very rarely find that I have to manipulate the RepeatCount property these days, so I wonder why you would want to do that?
That's probably the subject of a separate Stack Overflow question, though...

Is it possible to create eventlisteners for string, int, bool at all?

Is it possible at all to create eventlisteners (i.e. when the value changes) for a variable of type string, int, bool, etc.?
I haven't seen this in any programming language so far, except for some Collections (like ArrayCollection in Flex), which use events to detect changes in the collection.
If not possible at all, why not? What's the reason for this? Are there any best practices to achieve the same sort of functionality? And what about extending functionality with databinding?
I don't think there is anything by default, however, you can create a custom event and raise it on the set of the method. Something like...
C# example
public delegate void MyValueChangedEventHandler(bool oldValue, bool newValue);
public event MyValueChangedEventHandler MyValueChanged;
private bool myValue;
...
public bool MyValue
{
get { return myValue; }
set
{
if (myValue != value)
{
var old = myValue;
myValue = value;
MyValueChanged(old, myValue);
}
}
}
I guess this sort of functionality is not added in any framework/runtime since it would create a big overhead (think on how many times you modify a variable holding a primitive type within the average application) while being not used under normal circunstances.
Anyway, in .NET at least (and I guess that in other OO environments as well), you can define properties, which are accessed as normal variables but can have associated code that reacts when its value is read or modified.
It is possible if you wrap your variables in getters and setters and fire the event when the setter is called.
How about using setter methods and having them register events when changing the value of the variable?
In general, no. The reason is that primitive types are simply bits and bytes stored in some memory location: changing the data in that memory location does just that, and nothing else. Firing events would require calling some methods/functions. So the functionality can be achieved by wrapping the primitive types in some kind of wrapper objects - but of course, they're not 100 % interchangeable: for instance Java's primitive wrapper types (Integer etc.) are marked final, so it's not possible to extend them with event-firing versions to take advantage of auto(un)boxing.
Another approach is to poll the variable frequently and fire appropriate events if it has changed. This is a "dirty" approach with obvious disadvantages (performance overhead, not immediate reaction), but could regardless be useful in some situations. If you do this from another thread in Java, be sure to mark the variable volatile.
It is possible to create listeners, as some of ther others have mentioned, by making a class that fires an event whenever a property changes. This is obviously a lot less efficient than just assigning a value, but there are cases where it could be useful.
Some languages (VB6 and some others) have the ability in debug mode to stop execution when the value of a variable changes. I haven't seen this in .net, but it's liable to be in there somewhere. :-)
It seems to me that using an event to signal a simple variable change could be accomplished with if statements at each assignment, unless the value that variable is being changed externally, in which case you could use a class to handle it.

Why does VS2005 create both a member and a field for web service fields?

When adding a web reference in Visual Studio 2005, I've noticed that every element within the wdsl is duplicated. E.g. for element ItemOne, the interface it generates contains both ItemOne and itemOneField. Both are the same thing, but one is a member and the other is a field. I suspect the field is just a getter for the member.
I can imagine using a field instead of a member for this...but in that case my tendency would have been to make the member private, to avoid clutter. This, despite the fact that the normal motivation for making such a member private is to hide implementation details, which is obviously not applicable in this case.
I realize that changing this now would likely introduce compatibility issues, but I don't see why they did it this way the first time.
Do not point out that such a change would introduce compatibility issues with previous versions of VS. I am interested in the original reasoning behind this.
It's a property with a backing field. What's the problem? Were you expecting it to generate an automatic property? They didn't exist until recently. Why change what works, especially since ASMX (and WSDL.EXE) is pretty much dead technology.
"I am interested in the original reasoning behind this"
as everything past 3.0 framework, the only way to create properties were having a private variable and the property name
private string myItemField;
public string myItem() {
get {
return myItemField;
}
set {
myItemField = value;
}
}
but now, there is no need for it...
public string myItem { get; set; }
the thing is, that this last code is compiled as the original one at the top, even if it's easier to write, it is compiled in the same old way, you will end up with a private variable and a property.
Same thing happens when you add a Web Reference, it needs a variable to hold the "stuff" and then the method...

Resources