简体   繁体   English

以静态和非静态方法返回相同的生成的UUID

[英]Returning the same generated UUID in a static and non-static method

I have an object which is defined like so: 我有一个这样定义的对象:

TestDriver.java TestDriver.java

public void TestDriver extends FirefoxDriver implements SupportDownloads{

    public TestDriver(){
        super(TestDriver.service(), TestDriver.options());
    }

    private static service(){
        // implementation
    }

    private static options(){
        ..
        // attempting to generate a UUID which will be eventually be set as the folder where all downloads will go to. 
        // unique paths are needed as we will be using this class for multi-threaded runs and would like each browser to have its own unique download folder
        byte[] value = String.valueOf(Thread.currentThread().getId()).getBytes());
        String uniqueID = UUID.nameUUIDFromBytes(value).toString();
        ..
    }

    // purpose of this method is to return the path download folder 
    // note the repeated generation of the UUID because the above methods are static
    @Override
    public File getDownloadPath(){
        String value = String.valueOf(Thread.currentThread().getId());
        return new File(prop.getProperty(fileDirectory()) + File.separator + UUID.nameUUIDFromBytes(value.getBytes()));    
    }
}

SupportsDownload.java 支持下载

public interface SupportsDownload {
    public File getDownloadPath();
}

What I am trying to do is: 我正在尝试做的是:

  1. To generate a UUID so that each thread created have unique download paths 生成UUID,以便每个创建的线程都有唯一的下载路径
  2. To be able to also return this UUID in a public method which is accessible outside of this class (for unit-testing purposes and usage by the users) 为了也可以在此类之外可以访问的公共方法中返回此UUID(用于单元测试和用户使用)

Even though the above code is already working, I will run into an issue which official Java docs mention: 即使上面的代码已经起作用,我也会遇到官方Java文档提到的一个问题:

Returns the identifier of this Thread. 返回此线程的标识符。 The thread ID is a positive long number generated when this thread was created. 线程ID是创建此线程时生成的正整数。 The thread ID is unique and remains unchanged during its lifetime. 线程ID是唯一的,并且在其生命周期内保持不变。 When a thread is terminated, this thread ID may be reused. 当线程终止时,可以重新使用该线程ID。

As such, the above method is not foolproof because basing the UUID seed only on Thread.currentThread().getId() may yield the same ID if it is reused, causing the UUID generated to be the same. 因此,上述方法不是万无一失的,因为仅将UUID种子基于Thread.currentThread()。getId()才能在重用时产生相同的ID,从而导致生成的UUID相同。

I then tried to modify it to include time in millis, ie: 然后,我尝试将其修改为以毫秒为单位,即:

        byte[] value = String.valueOf(Thread.currentThread().getId() + Calendar.getInstance().getTimeInMillis()).getBytes());

However, as time value always changes, I wouldn't be able to grab the exact same value in the return method getDownloadPath() . 但是,由于时间值总是在变化,因此我将无法在返回方法getDownloadPath()获取完全相同的值。

If I were to generate the time value once, and store it in a variable, ie: 如果我只生成一次时间值,并将其存储在变量中,即:

private final long timeInMillis = Calendar.getTime().getTimeInMillis();

I will not be able to utilize this variable for both the static and non-static methods. 我将无法同时使用此变量的静态和非静态方法。

I'm at a loss, any suggestions would be great :-) 我很茫然,任何建议都会很棒:-)

I believe you should use ThreadLocal to do your task. 我相信您应该使用ThreadLocal来完成您的任务。 Below I have added a sample code. 在下面,我添加了示例代码。

public class Main {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            MyUUIDFactory.getUUIDPerThread();
            MyUUIDFactory.getUUIDPerThread();
        }, "My Thread-1");

        Thread t2 = new Thread(() -> {
            MyUUIDFactory.getUUIDPerThread();
            MyUUIDFactory.getUUIDPerThread();
        }, "My Thread-2");

        t1.start();
        t2.start();
    }

}

class MyUUIDFactory {
    private static final ThreadLocal<String> localWebDriver = ThreadLocal.withInitial(
            () -> UUID.randomUUID().toString());

    public static String getUUIDPerThread() {
        return localWebDriver.get();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM