/*
synchronized methods for use with shared Scanner objects used for type
conversion
963577
public synchronized Number convertToNumber(String s,
            NumberType numberType) {

        Number  number;
        boolean minus = false;
        Type    type;

        reset(s);
        resetState();
        scanWhitespace();
        scanToken();
        scanWhitespace();

        if (token.tokenType == Tokens.PLUS) {
            scanToken();
            scanWhitespace();
        } else if (token.tokenType == Tokens.MINUS) {
            minus = true;

            scanToken();
            scanWhitespace();
        }

        if (!hasNonSpaceSeparator && token.tokenType == Tokens.X_VALUE
                && token.tokenValue instanceof Number) {
            number = (Number) token.tokenValue;
            type   = token.dataType;

            if (minus) {
                number = (Number) token.dataType.negate(number);
            }

            scanEnd();

            if (token.tokenType == Tokens.X_ENDPARSE) {
                number = (Number) numberType.convertToType(null, number, type);

                return number;
            }
        }

        throw Error.error(ErrorCode.X_22018);
    }
1259687
private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        final java.io.ObjectOutputStream.PutField fields = s.putFields();
        final Object[] data;
        synchronized (this) {
            fields.put("capacityIncrement", capacityIncrement);
            fields.put("elementCount", elementCount);
            data = elementData.clone();
        }
        fields.put("elementData", data);
        s.writeFields();
    }
1108201
@Override
    public Iterator<Map<String, Object>> scan(String tableName, @Nullable String fromKeyExclusive,
                                              LimitCounter limit, ReadConsistency consistency) {
        return scan(tableName, fromKeyExclusive, limit, false, consistency);
    }
327922
@Override
    @SuppressWarnings({ "PMD.EmptySynchronizedBlock", "PMD.EmptyCatchBlock",
        "PMD.AvoidCatchingThrowable" })
    public void run() {
        try {
            registerAsGenerator();
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    selector.select();
                    Set<SelectionKey> selected = selector.selectedKeys();
                    for (SelectionKey key : selected) {
                        ((NioHandler) key.attachment())
                            .handleOps(key.readyOps());
                    }
                    selected.clear();
                    synchronized (selectorGate) {
                        // Delay next iteration if another thread has the lock.
                        // "Find bugs" complains, but this is really okay.
                    }
                } catch (InterruptedIOException | InterruptedException
                        | Error e) {
                    break;
                } catch (Throwable e) {
                    // Ignore anything else, this loop is crucial.
                }
            }
        } finally {
            unregisterAsGenerator();
        }
    }
902253
@InService(PageServiceImpl.class)
  static PageLeafImpl readCheckpointFull(TableKelp table, 
                                         PageServiceImpl pageActor,
                                         InputStream is,
                                         int pid,
                                         int nextPid,
                                         long sequence)
    throws IOException
  {
    byte []minKey = new byte[table.getKeyLength()];
    byte []maxKey = new byte[table.getKeyLength()];
    
    int count = 0;
    BlockLeaf []blocks;
    
    IoUtil.readAll(is, minKey, 0, minKey.length);
    IoUtil.readAll(is, maxKey, 0, maxKey.length);

    count = BitsUtil.readInt16(is);
    
    blocks = new BlockLeaf[count];
    
    for (int i = 0; i < count; i++) {
      blocks[i] = new BlockLeaf(pid);
      
      blocks[i].readCheckpointFull(is);
    }
    
    if (count == 0) {
      blocks = new BlockLeaf[] { new BlockLeaf(pid) };
    }

    PageLeafImpl page = new PageLeafImpl(pid, nextPid, sequence,
                                         table, minKey, maxKey, blocks);
    
    page.clearDirty();
    
    page.validate(table);
    page.toSorted(table);
    
    return page;
  }
808689
@SuppressWarnings("unchecked")
    private static synchronized Map<String, Boolean> getCache(GraphRewrite event)
    {
        Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);
        if (result == null)
        {
            result = Collections.synchronizedMap(new LRUMap(30000));
            event.getRewriteContext().put(ClassificationServiceCache.class, result);
        }
        return result;
    }
192484
public static synchronized <T> T invokeMethod(Object object, Class<?> declaringClass, String methodToExecute,
			Class<?>[] parameterTypes, Object... arguments) throws Exception {
		return WhiteboxImpl.invokeMethod(object, declaringClass, methodToExecute, parameterTypes, arguments);
	}
698270
private boolean isSyncCollectionCreation(int seen) {
        if (seen == Const.INVOKESPECIAL) {
            if (Values.CONSTRUCTOR.equals(getNameConstantOperand())) {
                return (syncCollections.contains(getClassConstantOperand()));
            }
        } else if ((seen == Const.INVOKESTATIC) && "java/util/Collections".equals(getClassConstantOperand())) {
            String methodName = getNameConstantOperand();
            return ("synchronizedMap".equals(methodName) || "synchronizedSet".equals(methodName));
        }
        return false;
    }
345337
synchronized Object getValue() {
        while (value == NULL) {
            try {
                wait();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
        }
        return value;
    }
679576
private Map<String, Object> getFieldValues(Object caller, ISyncHandler<?, ? extends ISyncableData> handler, String... syncNames)
	{
		Map<String, Object> values = new LinkedHashMap<>();
		for (String str : syncNames)
		{
			ObjectData od = handler.getObjectData(str);
			if (od != null)
				values.put(str, od.get(caller));
		}

		return values;
	}
906083
private void mergeInTransaction(EntityManager em, Collection objects) {
        EntityTransaction tx = null;
        try {
            tx = em.getTransaction();
            tx.begin();
            for (Object o : objects) {
                em.merge(o);
            }
            tx.commit();
        }
        catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                tx.rollback();
            }
            throw e;
        }
    }
482780
@Override
    public void readExternal(ObjectInput in)
        throws IOException, ClassNotFoundException {

        byte header = in.readByte();

        switch ((header & 0xFF) >> 4) {
            case FALLBACK_TIMEZONE_TYPE:
                this.obj = this.readFallback(in, header);
                break;
            case TRANSITION_RESOLVER_TYPE:
                this.obj = this.readStrategy(header);
                break;
            case HISTORIZED_TIMEZONE_TYPE:
                this.obj = this.readZone(in, header);
                break;
            case ZONAL_OFFSET_TYPE:
                this.obj = this.readOffset(in, header);
                break;
            default:
                throw new StreamCorruptedException("Unknown serialized type.");
        }

    }
1196145
@Override
    public void visitClassContext(ClassContext classContext) {
        try {
            if ((collectionClass != null) && (mapClass != null)) {
                collectionFields = new HashMap<>();
                aliases = new HashMap<>();
                stack = new OpcodeStack();
                JavaClass cls = classContext.getJavaClass();
                className = cls.getClassName();
                super.visitClassContext(classContext);
                for (FieldInfo fi : collectionFields.values()) {
                    if (fi.isSynchronized()) {
                        bugReporter.reportBug(new BugInstance(this, BugType.NMCS_NEEDLESS_MEMBER_COLLECTION_SYNCHRONIZATION.name(), NORMAL_PRIORITY)
                                .addClass(this).addField(fi.getFieldAnnotation()));
                    }
                }
            }
        } finally {
            collectionFields = null;
            aliases = null;
            stack = null;
        }
    }
1062258
@Override
    public void scan(ClassSource_Aggregate classSource, Set<String> specificClassNames) throws AnnotationTargets_Exception {
        try {
            createScanner(classSource).scan(specificClassNames);
            // 'createScanner' throws class source exception

        } finally {
            haveScannedDirectClasses = true;
            haveScannedReferencedClasses = true;
        }
    }
898661
public org.teatrove.tea.compiler.Scanner createScanner(SourceReader sr, CompilationUnit unit)
    throws IOException {
        org.teatrove.tea.compiler.Scanner scanner = super.createScanner(sr, unit);
        CompileListener scannerListener = getScannerListener();
        if (scannerListener != null) {
            scanner.addCompileListener(scannerListener);
        }
        return scanner;
    }
178308
@Override
	public synchronized RecordScan read(int scanId) throws DatabaseException {
    	SqlPreparedStatementWrapper psRead = null;
        try {
        	psRead = DbSQL.getSingleton().getPreparedStatement("scan.ps.read");
			psRead.getPs().setInt(1, scanId);
			
			try (ResultSet rs = psRead.getPs().executeQuery()) {
				return build(rs);
			}
		} catch (SQLException e) {
			throw new DatabaseException(e);
		} finally {
			DbSQL.getSingleton().releasePreparedStatement(psRead);
		}
	}
378788
@Override
    public void visitClassContext(ClassContext classContext) {
        try {
            JavaClass cls = classContext.getJavaClass();
            if (isSingleton(cls)) {
                syncBlockBranchResetValues = new HashMap<>();
                stack = new OpcodeStack();
                super.visitClassContext(classContext);
            }
        } finally {
            syncBlockBranchResetValues = null;
            stack = null;
        }
    }