我有以下java代码:
public class CheckInnerStatic {
private static class Test {
static {
System.out.println("Static block initialized");
}
public Test () {
System.out.println("Constructor called");
}
}
public static void main (String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
System.out.println("Inside main");
Class.forName("Test"); // Doesn't work, gives ClassNotFoundException
//Test test = new Test(); // Works fine
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不在class.forName("Test")这里工作,而下一行工作正常?
我需要懒洋洋地初始化地图及其内容.我现在有以下代码:
class SomeClass {
private Map<String, String> someMap = null;
public String getValue(String key) {
if (someMap == null) {
synchronized(someMap) {
someMap = new HashMap<String, String>();
// initialize the map contents by loading some data from the database.
// possible for the map to be empty after this.
}
}
return someMap.get(key); // the key might not exist even after initialization
}
}
Run Code Online (Sandbox Code Playgroud)
这显然不是线程安全的,如果一个线程来的时候someMap是空,继续初始化领域new HashMap和而其仍然在地图加载数据,另一个线程做了getValue,并没有得到数据时,人们可能已经存在.
如何在第一次getValue调用时确保数据仅在地图中加载一次.
请注意,key在所有初始化之后,地图中可能不存在.此外,在所有初始化之后,地图可能只是空的.
在perl中,我们可以做到:
使用lib LIST;
包含@INC中的路径列表.同样,我们可以这样做:
如果CONDITION,MODULE => ARGUMENTS,则使用;
有条件地包括一个模块.
是否有可能混合两者,比如
如果条件,列表使用lib;
有条件地包括路径列表.这似乎不起作用.
编辑:对不起,但我还是不能让它运转起来.这就是我在做的事情,但它不起作用.你能告诉我有什么问题吗?
use Data::Dumper;
BEGIN {
my $env=$ENV{'ENV'};
use if $env eq 'OLD', lib => '/home/vivek/OLD';
use if $env eq 'NEW', lib => '/home/vivek/NEW';
}
print Dumper \@INC;
Run Code Online (Sandbox Code Playgroud) 我正在以三种不同的方式将一些输出重定向到文件,并且每个输出都占用明显不同的时间.
$ >/tmp/file ; time for i in {1..1000}; do for j in {1..1000}; do echo $i $j >> /tmp/file; done; done
real 0m33.467s
user 0m21.170s
sys 0m11.919s
$ >/tmp/file ; exec 3>/tmp/file; time for i in {1..1000}; do for j in {1..1000}; do echo $i $j >&3; done; done; exec 3>&-
real 0m24.211s
user 0m17.181s
sys 0m7.002s
$ >/tmp/file ; time for i in {1..1000}; do for j in {1..1000}; do echo $i $j; done; done >> /tmp/file
real …Run Code Online (Sandbox Code Playgroud) 我想设定一年的年份java.util.Date.
我需要解析的时间戳不包括年份所以我这样做了:
private static final SimpleDateFormat logTimeStampFormat =
new SimpleDateFormat("MMM dd HH:mm:ss.SSS");
boolean isAfterRefDate (String line, Date refDate) {
try {
Date logTimeStamp = logTimeStampFormat.parse(line);
logTimeStamp.setYear(2012); // But this is deprecated!
return logTimeStamp.after(refDate);
} catch (ParseException e) {
// Handle exception
}
}
Run Code Online (Sandbox Code Playgroud)
为了避免使用弃用的方法,我喜欢这样:
private static final SimpleDateFormat logTimeStampFormat =
new SimpleDateFormat("MMM dd HH:mm:ss.SSS");
private static Calendar cal = Calendar.getInstance();
boolean isAfterRefDate (String line, Date refDate) {
try {
Date logTimeStamp = logTimeStampFormat.parse(line);
cal.setTime(logTimeStamp);
cal.set(Calendar.YEAR, 2012);
logTimeStamp = …Run Code Online (Sandbox Code Playgroud)