首页 \ 问答 \ 是否可以在用户代码中使用Java Unsafe?(Is it possible to use Java Unsafe in user code?)

是否可以在用户代码中使用Java Unsafe?(Is it possible to use Java Unsafe in user code?)

我正在读java.util.concurrent包中的代码,我发现类Unsafe(用于实现那些同步器)很有趣。 我可能永远不会在任何真正的代码中使用它,因为类名本身似乎不鼓励这样做,但出于好奇,我在这个课上有2个问题。

1)。 这个类的单例访问器是这样的:

    public static Unsafe getUnsafe() {
        Class cc = sun.reflect.Reflection.getCallerClass(2);
        if (cc.getClassLoader() != null)
            throw new SecurityException("Unsafe");
        return theUnsafe;
    }

因此,如果从用户代码调用此方法,则会抛出异常。 如何解决这个问题? (可能是通过bootstrap类加载器加载我自己的类?这可能吗?)

2)。 上面的代码假定getClassLoader将为boostrap类加载器加载的类返回null。 但是Class#getClassLoader的javadoc说“有些实现可能使用null来表示引导类加载器。”,这意味着在这个假设上没有保证。 对于违反此假设的实现,不安全(以及依赖于它的各种类,如ReentrantLock)根本不能工作吗?

谢谢!


I'm reading code in java.util.concurrent package, and i find the class Unsafe(which is used to implement those synchronizers) interesting. I may never use it in any real code because the class name itself seems to discourage doing that, but out of curiosity, i have 2 questions on this class.

1). The singleton accessor of this class is like this:

    public static Unsafe getUnsafe() {
        Class cc = sun.reflect.Reflection.getCallerClass(2);
        if (cc.getClassLoader() != null)
            throw new SecurityException("Unsafe");
        return theUnsafe;
    }

So if this method is invoked from user code, it will throw an exception. How to work around this? (possibly by making my own class loaded by the bootstrap class loader? is this possible?)

2). The above code assumes that getClassLoader will return null for classes that are loaded by the boostrap class loader. But the javadoc of Class#getClassLoader says "Some implementations may use null to represent the bootstrap class loader.", which means there is NO guarantee on this assumption. For implementations that do violate this assumption, wouldn't Unsafe(as well as various classes such as ReentrantLock that depends on it) fail to work at all?

Thanks!


原文:https://stackoverflow.com/questions/10829281
更新时间:2023-08-09 20:08

最满意答案

我只知道一个验证框架,即Enterprise Library Validation Application Block ,简称VAB。 我将从VAB的背景中回答您的问题。

第一个问题:你能在VAB中进行状态(场间)验证吗?

是的你可以。 有多种方法可以做到这一点。 您可以选择自我验证机制,如下所示:

[HasSelfValidation]
public class Range
{
    public int Min { get; set; }
    public int Max { get; set; }

    [SelfValidation]
    public void ValidateRange(ValidationResults results)
    {
        if (this.Max < this.Min)
        {
            results.AddResult(
                new ValidationResult("Max less than min", this, "", "", null));
        }
    }
}

我必须说我个人不喜欢这种类型的验证,特别是在验证我的域实体时,因为我喜欢将验证与验证逻辑分开(并保持我的域逻辑不受任何验证框架的引用)。 但是,它们需要的代码比替代方案少得多,后者正在编写自定义验证器类。 这是一个例子:

[ConfigurationElementType(typeof(CustomValidatorData))]
public sealed class RangeValidator : Validator
{
    public RangeValidator(NameValueCollection attributes)
        : base(string.Empty, string.Empty) { }

    protected override string DefaultMessageTemplate
    {
        get { throw new NotImplementedException(); }
    }

    protected override void DoValidate(object objectToValidate,
        object currentTarget, string key, ValidationResults results)
    {
        Range range = (Range)currentTarget;

        if (range.Max < range.Min)
        {
            this.LogValidationResult(results,
                "Max less than min", currentTarget, key);
        }
    }
}

编写此类后,您可以在验证配置文件中挂起此类,如下所示:

<validation>
  <type name="Range" defaultRuleset="Default" assemblyName="[Range Assembly]">
    <ruleset name="Default">
      <validator type="[Namespace].RangeValidator, [Validator Assembly]"
        name="Range Validator" />
    </ruleset>
  </type>
</validation> 

第二个问题:如何通过数据库(使用VAB)进行复杂的验证。

我给第一个问题的例子也可用于此。 您可以使用相同的技术:自我验证和自定义验证器。 您想要检查数据库中的值的方案实际上很简单,因为对象的有效性不是基于其上下文。 您只需根据数据库检查对象的状态即可。 当对象生存的上下文变得重要时(但VAB可能),它会变得更加复杂。 想象一下,例如,您想要编写一个验证,确保每个客户在给定的时间点,不超过两个未发货的订单。 这不仅意味着您必须检查数据库,而且可能在同一上下文中删除添加的新订单或订单。 此问题不是VAB特定的,您选择的每个框架都会遇到同样的问题。 我写了一篇文章 ,描述了我们在这些情况下面临的复杂性(阅读和颤抖)。

第三个问题:现实世界中的人们如何处理这种情况?

我在生产代码中使用VAB进行这些类型的验证。 它工作得很好,但VAB不是很容易学习。 尽管如此,我喜欢我们可以用VAB做什么,而且只有当v5.0问世时它才会变得更好。 如果您想学习它,请先阅读您可以在动手实验室下载中找到的ValidationHOL.pdf文档。

我希望这有帮助。


There's only one validation framework that I know well and that is Enterprise Library Validation Application Block, or VAB for short. I will answer your questions from the context of the VAB.

First question: Can you do state (between-field) validation in VAB?

Yes you can. There are multiple ways to do this. You can choose for the self validation mechanism, as follows:

[HasSelfValidation]
public class Range
{
    public int Min { get; set; }
    public int Max { get; set; }

    [SelfValidation]
    public void ValidateRange(ValidationResults results)
    {
        if (this.Max < this.Min)
        {
            results.AddResult(
                new ValidationResult("Max less than min", this, "", "", null));
        }
    }
}

I must say I personally don't like this type of validations, especially when validating my domain entities, because I like to keep my validations separate from the validation logic (and keep my domain logic free from references to any validation framework). However, they need considerably less code than the alternative, which is writing a custom validator class. Here's an example:

[ConfigurationElementType(typeof(CustomValidatorData))]
public sealed class RangeValidator : Validator
{
    public RangeValidator(NameValueCollection attributes)
        : base(string.Empty, string.Empty) { }

    protected override string DefaultMessageTemplate
    {
        get { throw new NotImplementedException(); }
    }

    protected override void DoValidate(object objectToValidate,
        object currentTarget, string key, ValidationResults results)
    {
        Range range = (Range)currentTarget;

        if (range.Max < range.Min)
        {
            this.LogValidationResult(results,
                "Max less than min", currentTarget, key);
        }
    }
}

After writing this class you can hook this class up in your validation configuration file like this:

<validation>
  <type name="Range" defaultRuleset="Default" assemblyName="[Range Assembly]">
    <ruleset name="Default">
      <validator type="[Namespace].RangeValidator, [Validator Assembly]"
        name="Range Validator" />
    </ruleset>
  </type>
</validation> 

Second question: How to do complex validations with possible interaction a database (with VAB).

The examples I give for the first question are also usable for this. You can use the same techniques: self validation and custom validator. Your scenario where you want to check a value in a database is actually a simple one, because the validity of your object is not based on its context. You can simply check the state of the object against the database. It gets more complicated when the context in which an object lives gets important (but it is possible with VAB). Imagine for instance that you want to write a validation that ensures that every customer, at a given moment in time, has no more than two unshipped orders. This not only means that you have to check the database, but perhaps new orders that are added or orders are deleted within that same context. This problem is not VAB specific, you will have the same problems with every framework you choose. I've written an article that describes the complexities we're facing with in these situations (read and shiver).

Third question: How do you people in the real world deal with this situation?

I do these types of validation with the VAB in production code. It works great, but VAB is not very easy to learn. Still, I love what we can do with VAB, and it will only get better when v5.0 comes out. When you want to learn it, start with reading the ValidationHOL.pdf document that you can found in the Hands-On Labs download.

I hope this helps.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。